问题
I have a PHP file that does data processing. It's run by $.ajax()
, sometimes on big files that take a long time to process. I need to log some info about the ongoing process in the browser console that is displayed on the go, not just when the PHP file has finished running.
From the research I did, I get that there are two difficulties:
- Getting PHP to spit out something before it's done
- Getting jQuery/JS to display it on the go
To address #1, I've tried:
echo "started"."<br>";
foreach (array("done this", "done that","had a coffee","burp") as $msg) {
sleep(3);
echo $msg."<br>";
flush();
ob_flush();
}
flush(); ob_flush();
is supposed to do the job, although as you can test here it does not strictly display ever 3s as it's expected to. Any suggestion to get it to display as expected?
As for how to address #2, I have explored a solution involving XMLHttpRequest
, but I'm not familiar with the subject so not sure neither what to look for nor if it's the right direction...
Here is the test code of what I'm trying to get to run:
$("#run").click(function(e) {
$.ajax({
url: "http://constances-web-dev.vjf.inserm.fr/constances-web/ajax-test.php",
xhr: function() {
// get the native XmlHttpRequest object
var xhr = $.ajaxSettings.xhr();
xhr.addEventListener('readystatechange', function(e) {
console.log(e)
});
// set the onprogress event handler
//xhr.onprogress = function(evt){ console.log(evt.target.response) } ;
// set the onload event handler
return xhr;
},
success: function(msg) {
console.log(msg);
},
error: function(msg) {
console.log("Erreur: " + msg);
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="run">go</button>
Subsidiary question: Is there an (easy) way to go around the cross-origin restriction in order to get an AJAX example to work in a SO snippet?
回答1:
as a work around I've added a log to file to my write2log function
static function log2File($string, $logFileName) {
if (substr($string,0,1 ) == "\n")
exec("echo '".date('Y-m-d_H:i:s')." ".addslashes(substr($string,1))."' >> ".$logFileName,$output,$status);
else
exec("echo -n ".addslashes($string)."' >> ".$logFileName,$output,$status);
}
I can then tail -f
the log to watch how things are going
but this takes ssh access to the server so i'd still be interested in figuring out how to log to console
来源:https://stackoverflow.com/questions/45863567/how-to-log-php-file-run-with-jquery-ajax-in-browser-console