并发Ajax调用 [英] concurrent ajax calls

查看:125
本文介绍了并发Ajax调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想jQuery的同时ajax调用做,但我还没有找到关于它的任何特殊。当我做2 Ajax调用,正在启动另外一个第一个完成之后。我试过 $ ajaxSetUp {(异步:真)} ,但它没有工作,我想要的方式。谁能帮我这个?

I am trying to do concurrent ajax calls in jquery but I haven't found anything specific regarding it. When I make 2 ajax calls, another one is being started only after the first one is finished. I tried $.ajaxSetUp{(async: true)}, but it didn't work the way i wanted. Can anyone help me with this?

我有一个表格和表格提交我用 form.js 的ajaxSubtmit我的格式有文件输入

I have a form and on form submit I use the ajaxSubtmit of form.js as my form has file input as well.

$("form").submit(function() {
  $(this).ajaxSubmit();
  $.getScript("url");
  return false; // to stop the normal working of form submit and submit form by ajax
})

这里的第二个AJAX被称为第一个完成后才能使用。

here the second ajax is called only after the first one is finished.

推荐答案

这就是你说的所谓竞争状态。 为了避免它,你有两个选择,要么你创建一个数组来存储每个请求,或创建用于存储每个请求的局部变量。 这里有一个简单的例子,避免竞争条件:

So that's what you said is called race condition. To avoid it you have two options, either you create an array to store each request, or you create a local variable to store each request. Here's a simple example that avoids the race condition:

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调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆