【问题标题】:How to convert fetch() to XML HTTP Requests?如何将 fetch() 转换为 XML HTTP 请求?
【发布时间】:2021-03-31 13:56:01
【问题描述】:

我有一些使用fetch() 的代码。我决定使用XMLHttpRequest() 而不是fetch(),但我找不到如何转换它。

这是我的fetch() 代码:

fetch("file.wasm")
    .then(response => response.arrayBuffer())
    .then(bytes => WebAssembly.instantiate(bytes,importObject))
    .then(results => callback(results.instance.exports));

我尝试将其转换为:

var x;
if(window.XMLHttpRequest)x=new XMLHttpRequest();
else x=new ActiveXObject("Microsoft.XMLHTTP");
x.onreadystatechange=function(){
    if(this.readyState!==4)return;
    if(this.status>=200&&this.status<300)
        callback(WebAssembly.instantiate(x.responseText.arrayBuffer(), importObject).instance.exports);
    else return "Error: "+this.status+" "+this.statusText;
}
x.open("GET","file.wasm");
x.send();

如果有点难以理解,这里是没有多余部分的代码:

var x = new XMLHttpRequest();
x.onreadystatechange=function(){
    if(this.readyState==4 && this.status===200)
        callback(WebAssembly.instantiate(x.responseText.arrayBuffer(), importObject).instance.exports);
}
x.open("GET","file.wasm");
x.send();

fetch()转换成XMLHttpRequest()的流程是什么?

编辑澄清:我的 (XMLHttpRequest) 代码不正确的原因是它给出了错误:

Uncaught TypeError: x.responseText.arrayBuffer is not a function
    at XMLHttpRequest.x.onreadystatechange (wasm.js)

x.onreadystatechange @ wasm.js

XMLHttpRequest.send (async)

(anonymous) @ wasm.js

【问题讨论】:

  • 转换它似乎很奇怪......

标签: javascript xmlhttprequest fetch-api


【解决方案1】:
request = new XMLHttpRequest();
request.open('GET', 'simple.wasm');
request.responseType = 'arraybuffer';
request.send();

request.onload = function() {
  var bytes = request.response;
  WebAssembly.instantiate(bytes, importObject).then(results => {
    callback(results);
  });
};

我从https://developer.mozilla.org/en-US/docs/WebAssembly/Loading_and_running这里举了一个例子

【讨论】:

    猜你喜欢
    • 2019-01-20
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2018-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多