提取responseJSON对象

Extracting responseJSON object

本文关键字:对象 responseJSON 提取      更新时间:2023-09-26

我对ajax和Javascript相当陌生我有这个代码

duration_reco = $.ajax({
    url : newurl, 
    dataType : 'json'
}).done(function (obj) {});
console.log(duration_reco);

我得到的输出是http://grab.by/v0lc我对responseJSON(快照中的最后一个对象)感兴趣。我试过duration_reco。responsejSON,但它不起作用。如何获取值

<标题>编辑

只是提供更多的代码,以便您可以更好地帮助

for(var i=1;i<=10;i++) 
{   
    duration_reco = $.ajax({
        url : newurl, 
        dataType : 'json'
    }).done(function (obj) {
        console.log(obj.data.duration); 
        //console.log(duration_reco.responseJSON());
        data[i - 1] = {
            "duration" : obj.data.duration
         };
     });
}

我试图做这样的事情,但似乎既不是' I '也不是'数据'是可访问的内部。还有哪些选项

您的Ajax请求正在异步完成,而您的代码正在线性执行。您需要在回调函数中记录输出。

var duration_reco = {};
$.ajax({
    url : newurl, 
    dataType : 'json'
}).done(function (obj) {
  duration_reco = obj;
  console.log(duration_reco);
});

您可以访问.done函数,其中obj是参数。

}).done(function (obj) {
    //console.log(obj); //your response
});

在整个问题的评论中,你说过"我想使它同步"answers"我可以在外部访问它"之类的话。您遇到的是学习者在处理异步代码时会遇到的一个非常常见的问题。你很恼火,因为你想写这样的代码:

  1. 设置呼叫
  2. 呼叫
  3. 处理结果

异步请求,你觉得,只是在妨碍。不要这样想!不要沮丧:了解问题所在,然后进行报复。这里有一个很好的资源链接,可以帮助你驯服异步代码。

Edit:使用您提供的示例代码,我制作了一个最小的示例,说明如何使用承诺设置这一切。查看工作小提琴

// global variables: find a better way!
var data = [];
var count = 0;
// a function that returns a promise can be "waited for"
var many_requests = function () {
    var promise = $.Deferred();
    for(var i = 0; i < 10; i++) {   
        make_one_request(i, promise);
    }
    return promise; // "I promise one day I'll be an array of responses"
};
var make_one_request = function (index, promise) {
    $.ajax({
        url : '/echo/json/', 
        dataType : 'json',
        method: 'post', // <---- I'm making a POST because this is a fiddle
                        //       you will still use a GET
        data: {}, // <-- your data here
        success: function (response) {
            // these will run out of order, but your array will be ordered
            data[index] = response;
            console.log(index);
            // if the time has come, resolve the promise
            count++;
            if (count == 10) {
                promise.resolve(data); // OK! I'm an array of responses now!
            }
        }
    });
};
// I will wait until I have an array of response data
$.when(many_requests()).then( function (data) {
    // woo!
    console.log(data); 
});

特别要注意success函数中的console.log语句。返回的结果是无序的,但是数组仍然按照正确的顺序被索引。then函数的回调只有在many_requests返回的承诺被解析后才会运行。

也许这对你有用,也许没用,但真正重要的是:当你遇到一种新的编程、一种新的模式或一种新的技术时……不要试图逃避并躲在你的旧模式中!拥抱新鲜有趣的东西,尽可能多地学习,然后选择你最喜欢的技术,把它们放在你的工具带里。