【问题标题】:XMLHttpRequest onprogress Uncaught SyntaxError: Invalid or unexpected tokenXMLHttpRequest onprogress Uncaught SyntaxError:无效或意外令牌
【发布时间】:2021-08-14 05:52:32
【问题描述】:

我有一个有效的 ajax 函数

但是当我使用 onprogress 时,有时会返回一半的 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) ; } } 更改.onprogress 我不会有控制台错误....但是有时,php 中发生的事情需要很长时间才能执行并想要显示进度。

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

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

问题:有没有办法避免在 onprogress(在 javascript 方面)出现“一半返回的 html”?

【问题讨论】:

  • 没有。 responseText 是原始文本缓冲区。不要使用任意 html 进行流式传输。把它分成几行,每行都是有效的html或类似的东西。
  • @Bergi 我刚刚看到你的意思,进一步挖掘我发现了这个“[Violation] Forced reflow while execution JavaScript take 36ms”所以这是一毫秒的事情
  • @Bergi 是否有一种 javascript 方式来“过滤”或“堆叠”缓冲区,而不是同时输出所有接收到的缓冲区?
  • 正如我所说,使用类似responseText.split('\n') 的内容并显示除最后(不完整)行之外的所有行。
  • @Bergi 您知道是否有任何方法可以避免“执行时重排”javascript 是否有某种方法可以检测到这一点?

标签: javascript ajax xmlhttprequest live


【解决方案1】:

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

它也适用于 webviews android 和 IOS ;)

在这个场景中,我的 PHP 8 和 NGINX 都关闭了输出缓冲区,因此在继续执行的同时推送每个回显......

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

}

【讨论】:

    猜你喜欢
    • 2020-07-12
    • 2017-09-29
    • 2018-12-03
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 2018-05-12
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多