使用Jquery将Ajax jsonp数据转换为数组



我创建了一个用于检索数据的jsonp请求。唯一的问题是我似乎无法在循环之外的数组中获取数据:(

var lookbook_data = new Array();
$.ajax({
  url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
    lookbook_data[i] = data.posts[i].custom_fields.image1[0];      
}
}
});
console.log(lookbook_data); 

因此,当我在look中console.log they数组时,它会以应有的方式输出数据。然而,在功能之外,它没有。但我确实去掉了外面的变量,所以我真的不明白为什么:(

顺便说一句,很抱歉,混乱的代码库似乎无法用4个空格完成:(

该ajax调用是异步的,因此您可以在代码完成之前立即到达代码的最后一行。

您可以使其与同步(不推荐)

async = 'false'

在ajax调用中

或者做一些类似的事情

$.ajax({
    url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
    dataType: "jsonp",
    success: function(data) {
        for(var i = 0; i<4; i++) {
            lookbook_data[i] = data.posts[i].custom_fields.image1[0];      
        }
        continueHere()
     }
 });
 function continueHere() {
      // rest of the code that handles your ajax call
 }
var lookbook_data = new Array(),
    XHR = $.ajax({
            url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
            dataType: "jsonp"
          });
//anywhere else in your script you can call :
XHR.done(function() {
    for(var i = 0; i<4; i++) {
        lookbook_data[i] = data.posts[i].custom_fields.image1[0];      
    }
    console.log(lookbook_data); 
});

在成功函数中的for循环console.log(lookbook_data[i]);中使用此函数

在成功函数中使用console.log(lookbook_data);

最新更新