简体   繁体   English

我们可以获取 Ajax 调用的状态,例如 20% 已完成吗?

[英]Can we get the status of Ajax call, like 20% completed?

Am calling an ajax call to validate n number of data.我正在调用 ajax 调用来验证 n 个数据。
Since it takes lot of time to complete, I thought of showing the user the progress bar or tell that 1/n completed由于需要很多时间来完成,我想到了向用户展示进度条或告诉1/n完成
In-order to display that, I should get the status from the controller.为了显示它,我应该从控制器获取状态。

Can someone please tell me is there any way to get the status from controller before completing?有人可以告诉我有什么方法可以在完成之前从控制器获取状态吗? Or Is there any other better way to implement.或者有没有其他更好的实现方式。

Since ordinary AJAX is a classic request-response you cannot get progress information from the server with the same connection. 由于普通的AJAX是经典的请求-响应,因此无法从具有相同连接的服务器获取进度信息。 You have to make a new AJAX call to ask the server for the task progress. 您必须进行新的AJAX调用,以询问服务器任务的进度。 This is called a heartbeat pooling technique. 这称为心跳池技术。

Better solution is to use some kind of persistent connection, for example Websockets. 更好的解决方案是使用某种持久连接,例如Websockets。 That way server can push a message with progress information to the client over the same connection that initiated the task. 这样,服务器可以通过启动任务的同一连接将带有进度信息的消息推送到客户端。 Websocket adoption is strong among browsers. Websocket在浏览器中的采用率很高。

You Could try the following : In the php file you request with your AJAX call you could set a $var that contains the process. 您可以尝试以下操作:在通过AJAX调用请求的php文件中,您可以设置一个包含该过程的$ var。 For Example you increment the var every 5 lines. 例如,您每5行增加var。 After increment you call a Function that do the Animation process or just echo the process status in percent . 递增后,您可以调用执行动画过程的函数,或者只是以百分比形式回显过程状态。

<?php

  $process = 0;


   function foo(){
      doSomething();
      $process++;
      showProcess();
   }

   function showProcess($process){
       echo $process;
      //some lazy effects 
   }
?>

Negative Aspect of this Method would be that (belongs to complexitivity) your programm will be a bit slower. 该方法的不利方面是(属于复杂性)您的程序会慢一些。

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

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