同时更新divs内容(嵌套的ajax调用)
我在这样的页面上有两个div:同时更新divs内容(嵌套的ajax调用),ajax,jquery,Ajax,Jquery,我在这样的页面上有两个div: <div id="content_1"></div> <div id="content_2"></div> $('#content_1').load('content_1_url', function(){ $.ajax({ type: 'GET', url: 'content_2_url', success: function(data) {
<div id="content_1"></div>
<div id="content_2"></div>
$('#content_1').load('content_1_url', function(){
$.ajax({
type: 'GET',
url: 'content_2_url',
success: function(data) {
$('#content_2').html(data);
}
});
});
$.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
}
如上所述,content\u 1
的内容来自对urlcontent\u url
的ajax调用的返回结果,content\u 2
的内容来自对urlcontent\u url
的ajax调用的返回结果。这很好,但我的问题是,页面上每个div的内容没有在完全相同的时间更新。第一个div内容首先显示,然后在一秒钟后显示第二个div的内容。我希望他们同时出现。你知道我该怎么解决这个问题吗
谢谢你那么:
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]);
});
像这样的
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);
试着这样做:
<div id="content_1"></div>
<div id="content_2"></div>
$('#content_1').load('content_1_url', function(){
$.ajax({
type: 'GET',
url: 'content_2_url',
success: function(data) {
$('#content_2').html(data);
}
});
});
$.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官方文档),只需将page1.php和page2.php更改为您的URL:
$.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!");
}
});
是否可以在不设置
async=false
的情况下执行此操作?是的,先生,@swead-answer在不设置async=false
的情况下执行此操作