【问题标题】:fetch stream html like ajax onprogress像ajax onprogress一样获取流html
【发布时间】: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


    【解决方案1】:

    :) 我找到了答案

    感谢这两个链接

    https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream

    Uint8Array to string in Javascript

    这里是混合和测试的

    php 可以推送任何带有 CSS 和 javascript 的 html,一旦它到达 YAY 就可以执行;)

    对 php 的测试是 echo some html、echo '1'、sleep(3) 并重复几次。

    当我触发“fetchsrteam”功能时,我会看到每个 echo 直播,我不必等待 php.ini 完成。这样我就可以看到正在发生的事情的反馈(罕见但可能)长 php 脚本,这些脚本从 API 检索信息、做事、计算等。

    ** 我也在 IOS 和 Android 的 webviews 中对此进行了测试;)

    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();
                }
              });
        });
    
    }
    

    这里的神奇之处在于这一行 $("#"+divid).append(new TextDecoder().decode(value)); ==>> new TextDecoder().decode(value) 包裹在 $("#id").append() .....

    玩得开心;)

    【讨论】:

    • 长时间执行 PHP 的示例:FFMPEG 通常可能需要很长时间才能完成,并且执行外部 js 来提供进度反馈有点困难,但在 PHP 中有一种方法可以回显 %在编码时完成,所以我们需要一个类似长拉或类似于 wss websocket 的东西,但在常规 HTML 中......
    猜你喜欢
    • 2016-08-02
    • 2012-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-18
    相关资源
    最近更新 更多