我怎么能叫AJAX不同步我的网页冻结我的、不同步、网页、我怎么能

2023-09-11 00:52:48 作者:梦游去告白

我有一些JavaScript代码触发了大约100个​​电话到PHP脚本。 PHP脚本使用了大量的内存和需要几秒钟就可以完成,然后返回合格或不合格的JSON响应。

我不希望Ajax调用是异步的服务器会来嘎然而止运行本身的100个实例,所以我试着用同步的,唯一的问题是它冻结的网页,而它调用脚本一个呼叫在时间

如何才能断火Ajax调用一次,而不是冻结页我敢吗?

 变种A = [];
    A [0] =测试;
    A [1] ='你好';
    一个[2] ='另一';

$(文件)。就绪(函数(){
  $每个(一,功能(K,V){
$阿贾克斯({
  网址:'/此脚本通吃A-几秒到complete.php,
  异步:假的,
  数据:{FOO:V},
  成功:功能(数据){
    的console.log(数据);
  }
});
  });
});
 

解决方案

您可以把一个函数来执行下一次调用,并从成功调用这个处理程序,像这样的:

  $(函数(){
  变种I = 0;
  传播nextCall(){
    如果(我==则为a.length)回报; //最后一次通话是在数组中的最后一个项目
    $阿贾克斯({
      网址:'/此脚本通吃A-几秒到complete.php,
      数据:{FOO:A [1 ++]},
      成功:功能(数据){
        的console.log(数据);
        nextCall();
      }
    });
  }
  nextCall();
});
 
AJAX 爬取AJAX数据

虽然...更好的方法是不会做100个电话,除非这是一个测试套件的一些排序,我会重新访问整个方法。

I have some javascript that fires off about 100 calls to a php script. the php script uses up a lot of memory and takes a few seconds to complete, then returns a json response of pass or fail.

I don't want the ajax calls to be asynchronous as the server would come to a grinding halt running 100 instances of itself, so I tried using synchronous, the only problem being it freezes the webpage while it calls the script one call at a time.

How can I fire off the ajax calls one at a time and not freeze the page i'm on?

var a = [];
    a[0] = 'test';
    a[1] = 'hello';
    a[2] = 'another';

$(document).ready(function(){ 
  $.each(a, function(k,v) {
$.ajax({
  url:'/this-script-takes-a-few-seconds-to-complete.php',
  async:false,
  data: {foo: v},
  success: function(data){      
    console.log(data);  
  }
});
  });
});

解决方案

You can put in in a function that performs the next call, and call this from your success handler, like this:

$(function(){ 
  var i = 0;
  function nextCall() {
    if(i == a.length) return; //last call was last item in the array
    $.ajax({
      url:'/this-script-takes-a-few-seconds-to-complete.php',
      data: { foo: a[i++] },
      success: function(data){      
        console.log(data);  
        nextCall();
      }
    });
  }
  nextCall();
});

Though...the better approach would be to not do 100 calls, unless this is a test suite of some-sort, I'd re-visit the whole approach.