并发ajax调用
我试图在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只在第一个完成后被调用。
所以你所说的就是竞争条件。 要避免它,您有两个选项,要么创建一个数组来存储每个请求,要么创建一个局部变量来存储每个请求。 这是一个避免竞争条件的简单示例:
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); }
两个Ajax调用都是独立的,如果第一个调用延迟完成,那么第二个调用是独立的,你可以调用你想要的多个调用ajax:10,20,30 ……
要更改方法,请使用以下function
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');});