如果这是一个重复的问题,我道歉,我遵循了另一个问题的一些步骤,这些步骤似乎对我没有帮助。我试图检索一些JSON数据,将部分数据存储到一个变量中,并在AJAX请求之外的单独函数中使用该变量。
我从json数据的预期响应是http://localhost:8000/tutorials/retrieve/?page=2(此响应显示,如果我记录AJAX代码中的变量),但是,当我尝试从另一个函数记录变量时,我得到的实际响应如下:
n。事件{originalEvent: MouseEvent,类型:"click",时间戳:1436727171161,jQuery21304066238570958376: true, toElement:div#loadmore.recentTutorials…}
下面是当前代码
var recentFirstPage = '';
function retrieveTutorials(){
$.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
**some unrelated parsing code here**
//Set the variable to what I need
recentFirstPage = data.next_page_url;
},
error: function() {
alert("An error occurred processing AJAX request.");
}
});
}
$('#main-content-wrap').on('click', '.recentTutorials', function(recentFirstPage){
//Does not return expected result
console.log(recentFirstPage);
});
当我点击. recenttutorials时,我希望控制台从JSON记录数据,但它没有。有人能帮我纠正错误吗?
它不记录JSON数据的原因是调用是异步的。这意味着function
将从上到下执行,而不会等待调用完成。
使用的一种方法是利用deferred
对象,在完成时返回promise
。您可以接受调用者函数的匿名函数,以便在单击范围内执行它的回调。
观察:
function retrieveTutorials(){
return $.ajax({
type: "GET",
url: "/tutorials/retrieve",
dataType: "json"
});
}
$('#main-content-wrap').on('click', '.recentTutorials', function(){
//store our function call as an ajax promise
var promise = retrieveTutorials();
//wait for the ajax to return so we can mutate the data
promise.done(function(data){
//now our data will be properly
recentFirstPage = data.next_page_url;
});
});
在我看来,您试图在ajax完成之前记录数据。最好使用延迟。试试这个:
function retrieveTutorials(){
return $.ajax({ // will return deferred object
type: "GET",
url: "/tutorials/retrieve",
dataType: "json",
success: function(data){
**some unrelated parsing code here**
//Set the variable to what I need
recentFirstPage = data.next_page_url;
},
error: function() {
alert("An error occurred processing AJAX request.");
}
});
}
$.when( retrieveTutorials() ).done(function ( data ) {
console.log(recentFirstPage);
});
单击处理程序中的参数是您棺材中的最后一颗钉子。它总是jquery事件,你根本不应该处理它。
您确实需要在处理程序中调用retrieveTutorials()函数,并且需要向它传递一个回调函数,该回调函数将在成功时执行。所以你的retrieveTutorials()函数看起来像这样:
function retrieveTutorials(success){
$.ajax({ type: "GET", url: "/tutorials/retrieve",
dataType: "json",
success: success,
error: function() { alert("An error occurred processing AJAX request.");
} }); }
和点击处理程序:
$('#main-content-wrap').on('click', '.recentTutorials', function(){
retrieveTutorials(function(data){
console.log(data.next_page_url);
});
});
你也可以在其他答案中使用所有基于承诺的善良,但上面的习语你会经常看到。