简体   繁体   English

使用AJAX从API获取数据

[英]Getting data from API with AJAX

I am trying to get data from API and display them using AJAX I have this code 我正在尝试从API获取数据并使用AJAX显示它们,我有此代码

 $(document).ready(function(){  
          $('.show').click(function(){     
          $.ajax({
           url: 'url',
           dataType: 'json',
           success: function(data) {
              var items = [];
              $.each(data, function(key, val) {

                items.push('<li id="' + key + '">' + val + '</li>');    

              });

              $('<ul/>', {
                 'class': 'interest-list',
                 html: items.join('')
              }).appendTo('body');

           },
          statusCode: {
             404: function() {
               alert('There was a problem with the server.  Try again soon!');
             }
           }
    });
    });
    });

I have this result: 我有这个结果:

[object Object],[object Object],[object Object],[object Object],

What must I fix in my code? 我必须在代码中解决什么?

$.each iterates over the array, and key was the index of the array, and val was the entire object $.each遍历数组, key是数组的索引,而val是整个对象

You could change this line of code 您可以更改此行代码

items.push('<li id="' + key + '">' + val + '</li>');

to

var key = Object.keys(val)[0];
items.push('<li id="' + key + '">' + val[key] + "</li>"); 

to just get the first key directly. 直接获得第一把钥匙。 Here is the documentation for Object.keys . 这是Object.keys的文档。

First of all, you'd better add the type:'GET' field to define what kind of call are you doing. 首先,最好添加type:'GET'字段来定义您正在执行的呼叫类型。 Then you can use var json = JSON.parse(data) to read all the incoming data from data like this: 然后,您可以使用var json = JSON.parse(data)data读取所有传入数据,如下所示:

var time = json['foo'];

or if you have an array: 或者,如果您有一个数组:

var time = json[index]['foo'];

you can find more details here https://www.w3schools.com/js/js_json_parse.asp and here https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse 您可以在这里https://www.w3schools.com/js/js_json_parse.asp和这里https://developer.mozilla.org/it/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse中找到更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM