【问题标题】:Drupal 7 : Flush () more than one response with AjaxDrupal 7:用 Ajax 刷新()多个响应
【发布时间】:2018-12-11 09:50:58
【问题描述】:

我有一个 Drupal 7 表单,在提交时我通过 Ajax 调用 PHP 函数,如下所示:

$('input[id*="edit-validate"]').click(function (e) {
        var uploadcvPath = Drupal.settings.basePath + 'myfunction_submit';
        $.ajax({
            url: uploadcvPath,
            data: $('form').serialize(),
            xhrFields: {
                onprogress: function (e) {
                    var thisResponse, response = e.currentTarget.response;
                    if (lastResponseLen === false) {
                        thisResponse = response;
                        lastResponseLen = response.length;
                    } else {
                        thisResponse = response.substring(lastResponseLen);
                        lastResponseLen = response.length;
                    }
                    jsonResponse = JSON.parse(thisResponse);
                    $('.ajax-res p').text('Processed ' + jsonResponse.count + ' of ' + jsonResponse.total);
                    $(".progress-bar").css('width', jsonResponse.progress + '%').text(jsonResponse.progress + '%');
                }
            },
            success: function (response) {
                    alert('Success!!');
            },
            complete: function () {
                //Hide loading container
                alert('Done!!');
            },
            error: function (xmlhttp) {
                alert('An HTTP error ' + xmlhttp.status + ' occurred.\n' + uploadcvPath);
            },
        });
             e.preventDefault();
    });

我想要做的是返回响应以提供进度条,所以我的 PHP 函数如下所示:

function myfunction_submit() {

  //First response
  drupal_json_output(array('progress' => 50, 'count' => 50, 'total' => 50));
  flush();
  ob_flush();
  sleep(2);

  //Seconde response
  drupal_json_output(array('progress' => 80, 'count' => 80, 'total' => 80));
  flush();
  ob_flush();
  sleep(2);

}

这仅适用于第一个响应,但是当我添加第二个响应时,我收到以下错误:

Uncaught SyntaxError: Unexpected token { in JSON at position 37 在 JSON.parse() 在 XMLHttpRequest.onprogress

位置 37 对应 JSON 响应中的 seconde {

{"progress":1,"count":1,"total":2}{"progress":2,"count":2,"total":2}

表示 Json 格式无效。 我的问题是:Drupal 7 中的 flush() 函数有问题吗?因为上面的代码可以在 Drupal 之外完美运行。

【问题讨论】:

    标签: php jquery ajax drupal flush


    【解决方案1】:

    如果有人遇到这个问题,我通过使用解决了它

    ob_end_flush(); 
    ob_flush(); 
    flush(); 
    ob_start()
    

    而不是

    flush();
    ob_flush();
    

    我希望有一天这对某人有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多