在Ajax Call

时间:2017-06-26 18:48:07

标签: php jquery ajax

我在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
        }
    }

这是我在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%
            }
        }
    });
});

此代码在执行和显示结果方面没有任何问题。

但是我希望从process.php连续获取输出json数据,以便在引导程序栏中以百分比单位显示每个$step的进程;

我找到了一些功能,例如ignore_user_abort()ob_clean()ob_flush(),但我不知道如何解决他们的问题。

我该怎么做?请帮我解决问题。 非常感谢。

1 个答案:

答案 0 :(得分:0)

有两种方法可以解决这个问题

  1. Websocket
  2. 长轮询
  3. 我将在这里描述长轮询方法:

    A, B = get1Ds(uniq_rows, test_rows)
    idx_group = []
    for row in A:
        idx_group.append(np.flatnonzero(B == row))
    

    Jquery不为 DECLARE @strTablename varchar(100) = 'dbo.test' DECLARE @strQuery varchar(max) = '' DECLARE @strSecondQuery varchar(max) = 'SELECT ' DECLARE @strUnPivot as varchar(max) = ' UNPIVOT ([Count] for [Column] IN (' SELECT @strQuery = ISNULL(@strQuery,'') + 'datalength([' + name + ']) as [' + name + '] ,' from sys.columns where object_id = object_id(@strTablename) and is_nullable = 1 SELECT @strUnPivot = ISNULL(@strUnPivot,'') + '[' + name + '] ,' from sys.columns where object_id = object_id(@strTablename) and is_nullable = 1 SET @strQuery = 'SELECT [Column],[Count] FROM ( SELECT ' + SUBSTRING(@strQuery,1,LEN(@strQuery) - 1) + ' FROM ' + @strTablename + ') AS p ' + SUBSTRING(@strUnPivot,1,LEN(@strUnPivot) - 1) + ')) AS unpvt ' EXEC (@strQuery ) 提供API(加载文档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(); } 对象

    XMLHttpRequest.readyState == 3