进程上的XMLHttpRequest未捕获语法错误:无效或意外的令牌



我有一个可用的ajax函数

但当我使用onpress时,有时会得到一半返回的html,控制台显示Uncaught SyntaxError: Invalid or unexpected token,但我还是继续。

这里是函数

function xhrAJAX ( divID , param2 ) {
var pcache = (Math.floor(Math.random() * 100000000) + 1);
var params = "divID="+encodeURIComponent(divID)+"&param2="+encodeURIComponent(param2);
var xhr = new XMLHttpRequest(); xhr.open("POST", "/file.php?pcache="+pcache, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onprogress = function(e) { $("#"+divID).html(e.currentTarget.responseText) ; }
xhr.send(params);
}

*****我知道如果我用xhr.onreadystatechange = function(e) { if (xhr.readyState == 4) { $("#"+divID).html(e.currentTarget.responseText) ; } }更改.onpress,我就不会出现控制台错误。。。。但有时,php中发生的事情需要很长时间才能执行,并且需要显示进度。

我的PHP8配置了NGINX,没有输出缓冲区,所以如果我执行echo 'stuff'; sleep(3); echo '2';,我会看到"stuff",然后在3秒钟后看到"2"出现。

请注意,这里描述的php部分不是问题所在。

问题:有没有办法避免";半返回html";在onprocress上(在javascript端(?

我找到了新的javascript替换fetch。经过一些挖掘,我想出了这个流式html

它也可以在webview android和IOS中工作;(

在这个场景中,我有PHP 8和NGINX,输出缓冲区关闭,所以在继续执行的同时推送每个echo。。。。

function fetchsrteam ( divid , sub , buttonid ) {

var pcache = (Math.floor(Math.random() * 100000000) + 1); 
var postix = [];
postix["preventCache"] = pcache;
postix["divid"] = encodeURIComponent(divid);
postix["buttonid"] = encodeURIComponent(buttonid);

fetch("/.........php?pcache="+pcache, {
method: "POST",
body: JSON.stringify(Object.assign({}, postix)),
headers: {"Content-type": "application/json; charset=UTF-8"}
}).then(response => response.body)
.then(rb => {
const reader = rb.getReader();
return new ReadableStream({
start(controller) {
function push() {
reader.read().then( ({done, value}) => {
if (done) {
console.log('done', done); controller.close(); return;
}
controller.enqueue(value); $("#"+divid).append(new TextDecoder().decode(value)); push();
})
}
push();
}
});
});
}

最新更新