作者:xkxk22 | 来源:互联网 | 2023-06-08 06:04
我想创建一个函数,该函数创建所需XMLHttpRequest的结构并将其输出为我可以使用的变量。我尝试使用以下代码进行此操作:
function prepareXMLHttpRequest(type) {
var targetURL = 'http://localhost:3000/';
var xhr = new XMLHttpRequest();
xhr.open(type,targetURL,true);
xhr.setRequestHeader('Content-Type','text/plain');
//set any other options here
return xhr;
}
我的意图是使用GET或POST调用该函数,然后发送结果:
prepareXMLHttpRequest("GET").then(function(getRequest) {
getRequest.send();
// Do something here,for example console.log the output
})
prepareXMLHttpRequest("POST").then(function(postRequest) {
postRequest.send(outputString);
})
当我尝试这些语句中的任何一条时,都会出现以下错误:
PrepareXMLHttpRequest(...).then is not a function
我在做什么错了?
另一种解决方案是使用fetch
API。这是一种更现代的XMLHttpRequest方法,默认情况下使用promise。
fetch("https://myapi.com")
.then(respOnse=> response.json())
.then(data => console.log(data))
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
,
您在做错的事情是期望XMLHttpRequest
具有then
属性,但事实并非如此。为了使函数的结果能够被接受,您需要返回如下的
function prepareXMLHttpRequest(type) {
var targetURL = 'http://localhost:3000/';
return new Promise((resolve,reject) => {
var xhr = new XMLHttpRequest();
xhr.open(type,targetURL,true);
xhr.setRequestHeader('Content-Type','text/plain');
xhr.addEventListener('readystatechange',event => {
event.readyState == 4 && event.status == 200 ? resolve(event) : reject(event)
});
xhr.send();
})
}
编辑:上面的代码段仅是出于示例目的,目的是一个很好的实现,该实现使用XMLHttpRequest()并返回Promise来看看whatwg-fetch