简体   繁体   English

jquery - 2 ajax 同时调用

[英]jquery - 2 ajax calls simultaneously

I want to run 2 AJAX calls simultaneously.我想同时运行 2 个 AJAX 调用。 I tried the below code but it waits for ajax ({export.php}) to finish and then ajax({display.php}) is run.我尝试了下面的代码,但它等待ajax ({export.php})完成,然后运行ajax({display.php})

I want to run these 2 AJAX calls at the same time.我想同时运行这 2 个 AJAX 调用。 For example, while export.php is running it should also run display.php at same time.例如,当 export.php 正在运行时,它也应该同时运行 display.php。 How can I do this?我怎样才能做到这一点?

When I click on a button it calls export.php to convert the database table to a CSV file.当我单击一个按钮时,它会调用 export.php 将数据库表转换为 CSV 文件。 I also want to show the progress bar ie how many records have finished, 1% , 2% ... 100% .我还想显示进度条,即完成了多少条记录, 1% , 2% ... 100% That percentage value is written in the display.php file so to make a progress bar I need to run the 2 AJAX calls simultaneously.该百分比值写入 display.php 文件中,因此要制作进度条,我需要同时运行 2 个 AJAX 调用。

$('.tocsv').on('click', function() {
  var display = setInterval(function() {
    $.ajax({
      url: 'display.php',
      method: 'get',
      success: function(data) {
        console.log(data);
      }
    });
  }, 500);

  $.ajax({
    url: 'export.php',
    method: 'post',
    success: function() {
      clearInterval(display);
    }
  });
});

Edit The problem was in display.php file i had written session_start() .编辑问题出在 display.php 文件中,我编写了session_start() I just deleted that line and changed ajax code to this我刚刚删除了该行并将 ajax 代码更改为此

                url: 'display.php?file=<?=session_id()?>',
                success: function (data) {
                    $('#res').html(data);
                }
            });

but why it doesn't work when i write session_start()?但是为什么当我写 session_start() 时它不起作用?

In AJAX the first alphabet A is for "Asynchronous".在 AJAX 中,第一个字母 A 表示“异步”。 So calling asyn way is not the issue here.所以调用异步方式不是这里的问题。 The problem is with making ajax request inside the setInterval.问题在于在 setInterval 内发出 ajax 请求。 I am very sure that you server is not responding in the time delay you have given ie 500ms and you are flooding your server with multiple request every half second.我非常确定您的服务器在您给定的时间延迟(即 500 毫秒)内没有响应,并且您每半秒就向您的服务器发送多个请求。 By the time one request is completed you have made at least 4 or 5 request to your server which is the root cause of you issue.当一个请求完成时,您已经向您的服务器发出了至少 4 或 5 个请求,这是您问题的根本原因。 Remove setInterval and if you want you call to be made after 0.5 sec use setTimeout.删除 setInterval,如果您希望在 0.5 秒后调用,请使用 setTimeout。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM