PHP flush information in controller

☆樱花仙子☆ 提交于 2019-12-11 12:56:07

问题


I am trying to send data to view from controller in PHP CodeIgniter.
I am calling the PHP function through ajax and using ob_flush to send data back but the problem is that all the flush calls are concatenated in later calls.

For example: the first flush send 1 second flush call send 12 instead of 2.

This is my controller loop.

foreach ($csv_array as $row) {
    ob_start();
    $varint=$varint+1;
    echo $varint;
    $content = ob_get_contents();
    ob_end_clean();
    echo $content;
    ob_flush();
    flush();
    while (ob_get_level() > 0) {
        ob_end_clean();
    }
}

My ajax call is this:

document.getElementById('upld').onclick = function() {
    xhr = new XMLHttpRequest();
    var mydata = new FormData($('#form')[0]);
    xhr.open("POST", base_url+"index.php/controller/function", true);
    xhr.onprogress = function(e) {
        console.log(e.currentTarget.responseText);
    }
    xhr.onreadystatechange = function(data='') {
        if (xhr.readyState == 4) {
            console.log(myArr);
        }
    }
    xhr.send(mydata);
};

回答1:


Documentation for flush() says:

flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

In your case you can replace flush() with ob_flush() as I don't think you are looking to flush the system output buffers.

As a little extra this code:

$content = ob_get_contents();
ob_end_clean();

Can be condensed into one function call that is an alias for both of the previous commands combined:

$content = ob_get_clean();

Documentation for ob_get_clean()



来源:https://stackoverflow.com/questions/35697301/php-flush-information-in-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!