我正在尝试在jquery中进行并发的ajax调用,但我没有找到任何具体的相关内容。当我进行2次ajax调用时,只有在第一次调用完成后才会启动另一个调用。我试过了$.ajaxSetUp{(async: true)}
,但它没有按照我想要的方式工作。任何人都可以帮我这个吗?
[编辑]
我有一个表单和表单提交我使用form.js的ajaxSubtmit,因为我的表单也有file input
。
$("form").submit(function() {
$(this).ajaxSubmit();
$.getScript("url");
return false; // to stop the normal working of form submit and submit form by ajax
})
这里第二个ajax仅在第一个ajax完成后被调用。
答案 0 :(得分:1)
这就是你所说的比赛条件。 要避免它,您有两个选项,要么创建一个数组来存储每个请求,要么创建一个局部变量来存储每个请求。 这是一个避免竞争条件的简单例子:
function customCallBack()
{// Ajax Status finished http status OK
if( (this.readyState == 4) && (this.status == 200) )
{
alert(this.responseText);
}
}
function anotherCallBack()
{// Ajax Status finished http status OK
if( (this.readyState == 4) && (this.status == 200) )
{
console.log(this.responseText);
}
}
function asyncPost(url, postArray, functionCallBack)
{
var request, query; //request must be a local var to avoid race condition
query = '';
for (i in postArray)//format post params
{
query += i + '=' + postArray[i] + '&';
}
try
{//for modern browsers
request = new XMLHttpRequest;
}
catch (err)
{// legacy IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
// your custom call back function
request.onreadystatechange = functionCallBack;
// type url true for async call, false for sync call
request.open("POST", url, true);
//Header sent to indicate a post form
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//making a post call
request.send(query);
};
//calling
asyncPost('yourUrl', {'field1' : 'value1', 'field2': 10}, customCallBack);
var post = new Array();
post['field1'] = 'value1';
post['field2'] = 10
//calling againg
asyncPost('anotherUrl', post, anotherCallBack);
// In jquery is like above, because you need the ajax call in a custom function
// and create a local var to hold your call:
function jqAjax(url)
{
var mycall = $.get(url);
}
答案 1 :(得分:0)
两个Ajax呼叫都是独立的,如果第一个呼叫延迟完成,那么第二个呼叫延迟独立,你可以拨打你想要的多个呼叫ajax:10,20,30 ......
要更改方法,请使用以下功能
function asyncCall(url, method, varArray, functionCallBack)
{
var request, query;
query = '';
for (i in postArray)//format params
{
query += i + '=' + postArray[i] + '&';
}
try
{//for modern browsers
request = new XMLHttpRequest;
}
catch (err)
{// legacy IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = functionCallBack;
if(method == 'GET')
{
request.open("GET", url + '?' + query, true);
request.send();
}
else
{
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(query);
}
};
console.log('start 1');
asyncCall('url1', 'GET', {foo : 'bar'}, function(){console.log('Call 1');});
console.log('start 2');
asyncCall('url2', 'POST', {foo : 'bar'}, function(){console.log('Call 2');});
console.log('start 3');
asyncCall('url3', 'POST', {foo : 'bar'}, function(){console.log('Call 3');});