【发布时间】:2021-08-23 13:52:14
【问题描述】:
是否可以对此进行简单的简单修改?
目标是在收到 html 时“绘制”它。
可能的场景:一个 php 需要 5 到 8 秒来执行,并在处理时推送每个 echo。
常规的 fetch.then 是 WAITING 等待所有行开始渲染。
我希望它在数据进入时尽快开始呈现。
我关闭了输出缓冲区的 nginx,这样当我在一个浏览器,我看到所有行都在显示,但 fetch 正在等待所有行。
这里是常规的 fetch.then(工作但等待)
// when I call this : it ask the php, php works, once php finished => boom => html render to a div ;)
function fetchajax (phpurl,stuff1,divid) {
var pcache = (Math.floor(Math.random() * 100000000) + 1); // random value to avoid cache reading
var postix = []; // prepare array for post body
postix["somestuff1"] = encodeURIComponent(stuff1);
postix["somestuff2"] = encodeURIComponent("test2");
fetch(phpurl+"?pcache="+pcache, {
method: "POST",
body: JSON.stringify(Object.assign({}, postix)), // transforms the array to be sent as body for the post request
headers: {"Content-type": "application/json; charset=UTF-8"}
}).then(function (response) { return response.text(); })
.then(function (html) { $("#"+divid).html(html); })
.catch( err => console.log() );
}
我在https://jakearchibald.com/2016/streams-ftw/ 找到了一些灵感,但我不知道我可以从哪个响应、结果、读者中取出 html...
// I want this to STREAM or render as soon as data is received to a div
function fetchajax (phpurl,stuff1,divid) {
fetch("/templates/account_ajax/topnavisub/"+sub+".php?pcache="+pcache+"&fetchx="+pcache, {
method: "POST",
body: JSON.stringify(Object.assign({}, postix)),
headers: {"Content-type": "application/json; charset=UTF-8"}
}).then(function(response) {
var reader = response.body.getReader();
var bytesReceived = 0;
reader.read().then(function processResult(result) {
if (result.done) { console.log("Fetch complete");return;}
bytesReceived += result.value.length;console.log(response,result,reader);
$("#"+divid+"_message").append('. ');
return reader.read().then(processResult);
});
});
}
有了这个,我在 php 的处理过程中看到了点;)但是如何在那里有文本或响应正文?
你可以在那里看到这个例子https://jsbin.com/vuqasa/edit?js,console
【问题讨论】:
标签: html stream fetch fetch-api fileoutputstream