1

我的 php 服务器有问题(我的电脑是唯一的连接)。我最初认为部分原因是因为 ajax 请求太多(我有一个脚本,每次击键都会执行一个 ajax 请求),所以我实现了一个设计来控制 ajax 请求进入队列的流程。下面是我的代码:

//global vars:
activeAjaxThread = 0; //var describing ajax thread state
ajaxQue = [];  //array of ajax request objects in queue to be fired after the completion of the previous request

function queRequest(ajaxObj) {
  ajaxQue.push(ajaxObj);
  if (activeAjaxThread == 0) {
    fireOffAjaxQue();   
  } else {
    return 'ajax thread is running';
  }
}

function fireOffAjaxQue () {
  activeAjaxThread = 1;
  //getLastRequest();
  if ((ajaxQue.length > 0) && activeAjaxThread == 1) {
    $.ajax(ajaxQue[0]).always( function () {
      ajaxQue.shift(); 
      if (ajaxQue.length > 0) {
        fireOffAjaxQue();   //fire off another ajax request since this one has been completed. 
      }
    });
  }
  activeAjaxThread = 0;   //thread has finished executing
}

执行:

//create ajax object
var ajaxObj = {
  url: 'someplace.php',
  data: dataVar,
  success: function (data) {...}
};
//send ajax object to que
queRequest(ajaxObj);

然后我发现 Javascript 是多线程的,并阅读了一些关于 Javascript 事件处理的文章,例如John Resig在http://ejohn.org/blog/how-javascript-timers-work/上的这篇文章(jQuery extra-ordinaire )

既然如此,难道我在这里介绍的函数不会产生任何结果,因为 Javascript 已经在排队我的请求了吗?奇怪的是,它似乎彻底改变了它。我的服务器崩溃较少,(并不是说它认为它是任何想象中的解决方案......),并且在它崩溃并重新启动后,先前排队的 ajax 请求被发送,而早些时候它们似乎都被一次发送并在服务器崩溃时消失得无影无踪。

如果 Javascript 是单线程的,对异步事件进行排队:

  1. 拥有 Ajax 请求管理器或队列有什么意义?
  2. 为什么我的代码会产生任何结果?
4

1 回答 1

4

Javascript is single threaded, but once the AJAX request is sent, it is out of javascript's hands, so to speak. That's the Asynchronous part of AJAX. The request is made and then the code moves on. Then when the response is received it is processed. Requests are not queued.

于 2013-02-12T21:02:42.777 回答