2013-07-02 50 views
1

我有一个页面上的两个div像这样:更新div的内容在同一时间(嵌套的AJAX调用)

<div id="content_1"></div> 
<div id="content_2"></div> 

那两个div的内容是通过Ajax更新通过做这样的事情:

$('#content_1').load('content_1_url', function(){ 
    $.ajax({ 
     type: 'GET', 
     url: 'content_2_url', 
     success: function(data) { 
      $('#content_2').html(data); 
     } 
    }); 
}); 

正如你可以看到上面的content_1内容来自Ajax调用的URL content_1_url的返回结果,并content_2内容来自Ajax调用的url content_2_url的返回结果。这工作正常,但我遇到的问题是每个div的内容不会在页面上同时更新。第一个div内容首先显示,然后一秒钟后显示第二个div的内容。我希望他们同时出现。任何想法如何我可以解决这个问题吗?

谢谢

回答

0

什么有关:

var ajax1 = $.ajax({ 
    type: 'GET', 
    url: 'content_1_url' 
}), ajax2 = $.ajax({ 
    type: 'GET', 
    url: 'content_2_url' 
}); 

$.when(ajax1,ajax2).done(function(data1,data2){ 
    $('#content1').html(data1[0]); 
    $('#content2').html(data2[0]); 
}); 
0

像这样的事情?

var res1, res2; 
$.ajax({type: 'GET', url: 'content_1_url', success: function(data){res1 = data;}, async: false}); 
$.ajax({type: 'GET', url: 'content_2_url', success: function(data){res2 = data;}, async: false}); 
$('#content1').html(res1); 
$('#content2').html(res2); 
+0

反正有没有设置'async = false'可以完成? – user765368

+0

是的,先生,@roasted答案是这样做的,而不'async = false' – Aguardientico

0

尝试这样:

$.when($.ajax("content_1_url"), $.ajax("content_1_url")) 
    .then(myFunc, myFailure); 

function myFunc(){ 
//This execute after both ajax calls finish ok 
} 

function myFailure(){ 
//This execute after either ajax calls fails 
} 

我编辑这是完整的代码(从jQuery的公报文件http://api.jquery.com/jQuery.when/)只是改变page1.php中则page2.php到你的网址:

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){ 
    /* a1 and a2 are arguments resolved for the 
     page1 and page2 ajax requests, respectively. 
     each argument is an array with the following 
     structure: [ data, statusText, jqXHR ] */ 
    var data = a1[0] + a2[0]; /* a1[0] = "Whip", a2[0] = " It" */ 
    if (/Whip It/.test(data)) { 
    alert("We got what we came for!"); 
    } 
});