2013-04-29 93 views
1

下面您可以看到我在做一个简单的ajax调用。但是,调用成功完成后,我想从页面中删除加载器div。问题是成功功能不会触发,为什么?当完成ajax调用时,jquery成功不运行

utils.get_do stuff = function AJAX_do stuff() {  
    $.getJSON('/url//', 
     function (data) { 
      $.each(data, function (key, val) { 
       // I do stuff with the data here. 
      }); 
     }, 
     function (success) { 
      $('#loader').hide(); 
     } 
    ); 
}; 
+5

['$ .getJSON()'](http://api.jquery.com/jQuery.getJSON/)不接受2个回调参数。阅读文档。 – 2013-04-29 15:21:09

+0

你想要用第一个函数填充数据参数,还是用它来处理AJAX结果? – Alnitak 2013-04-29 15:27:47

回答

4

这里是getJSON一个例子,我想你要隐藏在整个处理程序$('#loader'),所以$('#loader')隐藏不管请求失败或成功。

$.getJSON("/sms/fetch_smartpages/", function() { 
    console.log("success"); 
     $.each(data, function (key, val) { 
     //I do stuff with the data here. 
     }); 
     $('#loader').hide(); //<==== moved from here 
    }) 
    .done(function() { console.log("second success"); }) 
    .fail(function() { console.log("error"); }) 
    .always(function() { 
       console.log("complete"); 
       $('#loader').hide(); // moved here 
    }); 

http://api.jquery.com/jQuery.getJSON/

2
$.getJSON('/sms/fetch_smartpages/', 

// This callback function is executed if the request succeeds. 
function(data) { 

    $.each(data, function(key, val) { 
    // I do stuff with the data here. 
    }); 

    // Hide loader here 
    $('#loader').hide(); 
}); 
1

http://api.jquery.com/jQuery.getJSON/

$.getJSON('/sms/fetch_smartpages/',function (data) { // <-- this is your success handler 
     $.each(data, function (key, val) { 
     I do stuff with the data here. 
     }); 
     $('#loader').hide(); 
}); 
1
$.getJSON("example.json", function() { 
    console.log("success"); 
}) 
.done(function() { console.log("second success"); }) 
.fail(function() { console.log("error"); }) 
.always(function() { console.log("complete"); }); 
1

我怀疑你有误解的第二个参数的目的$.getJSON() - 它通常包含用于将传递到远程服务器供应数据的JS对象。

因为您已经传递了一个函数引用,它被用作“成功”回调函数,而第三个参数被忽略。

如果你真的想使用两个单独的“成功”回调,您可以使用.done(f1, f2)

注意两个功能将被传递标准(response, status, jqXHR)组参数。