Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以使用标准JavaScript函数创建XMLHttpRequest吗?_Javascript_Asynchronous - Fatal编程技术网

我可以使用标准JavaScript函数创建XMLHttpRequest吗?

我可以使用标准JavaScript函数创建XMLHttpRequest吗?,javascript,asynchronous,Javascript,Asynchronous,我想创建一个函数,该函数创建所需XMLHttpRequest的结构,并将其作为变量输出,以便使用。我已尝试使用以下代码执行此操作: function prepareXMLHttpRequest(type) { var targetURL = 'http://localhost:3000/'; var xhr = new XMLHttpRequest(); xhr.open(type, targetURL, true); xhr.setRequestHeader('Content

我想创建一个函数,该函数创建所需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

我做错了什么?

您做错的是希望
XMLHttpRequest
具有
then
属性,但它没有。为了使函数的结果能够实现,您需要返回一个如下所示的承诺

函数prepareXMLHttpRequest(类型){
var targetURL=http://localhost:3000/';
返回新承诺((解决、拒绝)=>{
var xhr=new XMLHttpRequest();
打开(类型,targetURL,true);
setRequestHeader('Content-Type','text/plain');
xhr.addEventListener('readystatechange',事件=>{
event.readyState==4&&event.status==200?解析(事件):拒绝(事件)
});
xhr.send();
})

}
另一种解决方案是使用
fetch
API。这是一种更现代的XMLHttpRequest方法,默认使用承诺

fetch("https://myapi.com")
    .then(response => response.json())
    .then(data => console.log(data))

是否会在承诺完成之前拒绝承诺,即,
readyState
不是4?@phuzi是的,我的想法是不展示良好的实现。这只是promiseFair的一个简单例子,但我可以看到OP问另一个问题,为什么承诺永远无法得到解决。就我个人而言,我会使用
onload
onerror
来触发
resolve
reject
respectively@Phil就我个人而言,我会使用许多优秀的开源库中的一个,但你可以自由编辑并添加到我的答案中:你不会返回一个
承诺
。使用…准备
XMLHttpRequest
不是一个异步过程,因此没有必要尝试将其初始化。您最好只使用
const getRequest=prepareXMLHttpRequest('GET')