2011-10-12 113 views
1

我有一个表,其中每一行都有一个触发AJAX调用的按钮。调用相同的功能但不同的参数。结果显示在与调用相同的行中。同一个js函数可以同时进行AJAX调用吗?

该通话可以提高速度,因此可能需要一分钟左右的时间。我可以观察到,如果我在前一个完成之前发起新的AJAX呼叫,我将失去呼叫的结果。

有什么办法可以我可以在同一个时间运行多个AJAX调用,并从调用中获得结果并显示它们?

  • 使用jQuery
  • 同一浏览器窗口
  • 调用PHP

HTML代码调用JavaScript的

<button type="button" onclick="update_revision(\'' . $directory . '\',\''.$server_name.'\')" > update </button> 

的Javascript

function update_revision(revision,server_name) 
    { 
     if (window.XMLHttpRequest) 
     {// code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp=new XMLHttpRequest(); 
     } 
     else 
     {// code for IE6, IE5 
     xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
     xmlhttp.onreadystatechange=function() 
     { 
     if (xmlhttp.readyState==4 && xmlhttp.status==200) 
      { 
      document.getElementById("rev."+revision).value="updated to "+update_to; 
      } 
     } 
     xmlhttp.open("GET","https://"+server_name+"/imacs/radek/svn_update.php?code_base="+revision+"&revision="+update_to+"&t=" + Math.random(),true); 
     xmlhttp.send(); 
    }   
+1

只需停止使用全局变量。您可以覆盖'xmlhttp',这样每当您的XHR对象的状态发生变化时,'onreadystatechange'就会检查您创建的* last *的条件。 – Quentin

+0

@Quentin:你能详细解释一下吗?我不明白... – Radek

回答

3

问题是,您正在使用单个全局变量来存储所有的XMLHttpRequest实例。无论何时创建新实例并将其引用存储在全局变量xmlhttp中,之前引用的以前的实例都会变为未引用,因此只要浏览器认为合适,它就会被垃圾收集。通常这意味着它立即被垃圾收集;在你的情况下,即使在收到待处理的响应之前,它也会被垃圾收集。

解决此问题的一种方法是在update_revision()函数中声明xmlhttp作为局部变量。就像这样:

function update_revision(revision, server_name) { 
    // declare xmlhttp locally 
    var xmlhttp; 

    if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari 
     xmlhttp = new XMLHttpRequest(); 
    } 
    else { // code for IE6, IE5 
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    xmlhttp.onreadystatechange = function() { 
     if (xmlhttp.readyState == 4) { 
      if(xmlhttp.status == 200) { 
       document.getElementById("rev." + revision).value = "updated to " + update_to; 
      } 

      // explicitly drop the reference when 
      // we're done with it, so the browser will reclaim the object 
      // (this is optional, but it's a good idea) 
      xmlhttp = null; 
     } 
    } 
    xmlhttp.open("GET", "https://" + server_name + "/imacs/radek/svn_update.php?code_base=" + revision + "&revision=" + update_to + "&t=" + Math.random(), true); 
    xmlhttp.send(); 
} 

注:

  1. xmlhttp被声明为一个局部变量

  2. xmlhttp被 “归零” 的时候,我们不需要它了(的readyState == 4后)。这将导致浏览器垃圾收集请求实例,从而防止资源泄漏。这是一个很好的做法(所以我已经在上面的例子中展示了它),但从技术上讲它是可选的。

+0

很好的解释。不,我明白了。如果我使用jQuery而不是纯粹的JavaScript呢? – Radek

相关问题