简体   繁体   English

在Ajax调用中连续获取PHP循环数据

[英]Continuously get PHP loop data in Ajax Call

I have this codes in process.php : 我在process.php有此代码:

$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
   $user_email = get_user_email($r); // Get email of each user
   if (!empty($user_email)) {
      send_w_mail(); // Send email to each user
      $step++;
      echo json_encode(
             ['step' => $step, 'all' => count($users)]
           ); // echo output
        }
    }

And this is my ajax call in index.php : 这是我在index.php ajax调用:

$("#send-message").click(function () {
    $.ajax({
        url: global_base_url + 'process.php', // global_base_url defined.
        async : true,
        type: 'POST',
        data: {'users': input_users}, // input_users is val() of a input.
        encoding: 'UTF-8',
        success: function (data) {
            data = $.trim(data);
            if (data){
                data = $.parseJSON(data);
                var p_value = parseInt(data.step*100)/data.all;
                set_progressbar_value(p_value); // set progressbar value. sample: 23%
            }
        }
    });
});

This codes don't have any problem for execute and showing result. 该代码对于执行和显示结果没有任何问题。

But I want to Continuously get output json data from process.php in order to show process of each $step in Percent unit in a bootstrap process-bar; 但是我想process.php 连续获取输出json数据 ,以便在引导过程栏中显示Percent单元中每个$step过程;

I found some function like ignore_user_abort() , ob_clean() and ob_flush() but don't know how can I solve my problem with them. 我发现了一些函数,例如ignore_user_abort()ob_clean()ob_flush()但不知道该如何解决它们的问题。

How Can I do this? 我怎样才能做到这一点? Please help me to solve the problem. 请帮我解决问题。 Thanks a lot. 非常感谢。

There are two ways of approaching this problem 有两种方法可以解决此问题

  1. Websocket 的WebSocket
  2. Long polling 长时间轮询

I will be describing the long polling method here: 我将在这里描述长轮询方法:

$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
    $user_email = get_user_email($r); // Get email of each user
    if (!empty($user_email)) {
        send_w_mail(); // Send email to each user
        $step++;
        echo json_encode(
            ['step' => $step, 'all' => count($users)]
        ); // echo output
        //Flush the output to browser
        flush();
        ob_flush();
    }

Jquery does not provide api for XMLHttpRequest.readyState == 3 (Loading docs here ) so we need to use raw XMLHttpRequest object jQuery不为XMLHttpRequest.readyState == 3提供api( 在此处加载文档),因此我们需要使用原始XMLHttpRequest对象

$("#send-message").click(function () {
    var prev_response = "";
    var xhr = new XMLHttpRequest();
    xhr.open("POST", global_base_url + 'process.php', true);

    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    xhr.onreadystatechange = function() {//Call a function when the state changes.
        if(xhr.readyState == 3) {
            // Partial content loaded. remove the previous response   
            var partial_response = xhr.responseText.replace(prev_response,"");
            prev_response = xhr.responseText;
            //parse the data and do your stuff
            var data = $.parseJSON(partial_response);
            var p_value = parseInt(data.step*100)/data.all;        
            set_progressbar_value(p_value); 
        }
        else if(xhr.readyState == 4 && xhr.status == 200){
            set_progressbar_value(100);
            console.log("Completed");
        }

    }
    xhr.send("users="+ input_users); 

});

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

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