【问题标题】:jQuery mobile: Wait until $.getJSON is finishedjQuery mobile:等到 $.getJSON 完成
【发布时间】:2013-08-29 04:58:01
【问题描述】:

我想用$.getJSON 调用填充一个表:

$.getJSON("localhost/url",
function (data) {
    $.each(data.reporting_list.reporting, function (i, item) {
        rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
    });
    $('#aaa').append(rows);
});

填充后我想触发一些页面更改:

$.mobile.changePage("#homePage");

但在 $.getJSON 完成之前页面会发生变化。
我只想在 $.getJSON 完成后更改页面并改为显示 ajaxloader。

【问题讨论】:

    标签: jquery json jquery-mobile asynchronous jquery-callback


    【解决方案1】:

    做

    $.getJSON("localhost/url", function (data) {
        $.each(data.reporting_list.reporting, function (i, item) {
            rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
        });
        $('#aaa').append(rows);
        //move to the page in the callback itself
        $.mobile.changePage("#homePage");    
    });
    

    【讨论】:

    • 正是你想要的我希望
    【解决方案2】:

    虽然Arun P Johny已经给出了答案,但是我只是想更清楚一点,jQuery中$.get()方法的正确用法

    根据http://api.jquery.com/jQuery.get/#jQuery-get1$.get()的方法其实是

    jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
    

    Where 这两个块,即data和success,只会在请求完成时调用,所以你可以在任一块中调用这个函数$.mobile.changePage("#homePage");

    即在function (data) { } 块中,如建议的Arun P Johny,或者您可以在下面的任何其他回调中调用它。

    var jqxhr = $.get("example.php", function() {
      alert("success");
    })
    .done(function() { alert("second success"); })
    .fail(function() { alert("error"); })
    .always(function() { alert("finished"); });
    

    与$.ajax() 一样,上述回调分别作为success error 和complete 工作

    希望对你有帮助

    【讨论】:

      【解决方案3】:
      ajaxcall(function(){ $.mobile.changePage("#homePage");});
      
      function ajaxcall(callback){
      $.getJSON("localhost/url", function (data) {
          $.each(data.reporting_list.reporting, function (i, item) {
              rows = '<tr><td>' + item.data1 + '</td><td>' + item.data2 + '</td></tr>'
          });
          $('#aaa').append(rows);
          //move to the page in the callback itself
          callback();
      });
      

      也可以使用回调函数,你也可以这样尝试

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-02
        • 2015-03-11
        • 1970-01-01
        • 2013-11-23
        • 1970-01-01
        • 2018-01-19
        相关资源
        最近更新 更多