从json jQuery中检索数据

时间:2018-03-19 01:20:50

标签: jquery json ajax

我在下面有这个JSON响应,我想避免前四个属性并使用数据数组中的属性。

JSON响应是

    {
   "page":2,
   "per_page":3,
   "total":12,
   "total_pages":4,
   "data":[
      {
         "id":4,
         "first_name":"Eve",
         "last_name":"Holt",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/marcoramires/128.jpg"
      },
      {
         "id":5,
         "first_name":"Charles",
         "last_name":"Morris",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/stephenmoon/128.jpg"
      },
      {
         "id":6,
         "first_name":"Tracey",
         "last_name":"Ramos",
         "avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/bigmancho/128.jpg"
      }
   ]
}

以下是jQuery 3.3.1代码

$.ajax({
    method: 'GET',
    url: 'https://reqres.in/api/users?page=2',
    success: function(data) {
      $.each(data,function(i,data){
        $data.append('<li><strong>First Name</strong> :  '+ data.first_name+ '</br>'+'<strong>Last Name</strong> :  '+ data.last_name +'</li>');

        console.log( this.first_name);    
    });
},
error: function() {
    alert('error loading data');
}

1 个答案:

答案 0 :(得分:1)

正如@MojoAllmighty在下面说的那样工作正常.Data.data获取JSON响应的数组

$.each(data.data,function(i,data){
  $data.append('<li><strong>First Name</strong> :  '+ data.first_name+ '</br>'+'<strong>Last Name</strong> :  '+ data.last_name +'</li>');
});