jQuery .ajax到Vanilla JavaScript

时间:2018-07-17 22:36:33

标签: javascript ajax

我正在尝试将ajax请求转换为原始JavaScript

$.ajax({
    url: 'http://foo.bar/hi',
    type: 'post',
    data: {args: params},
    success: function(data){
    },
});

我尝试了以下

var xhr = new XMLHttpRequest();
var data = {args: params};
xhr.open("POST", 'http://foo.bar/hi', true);
xhr.send(data);

我正在使用基于Web的界面连接到外部设备,但在该设备上未得到任何响应。好像我从未发送过请求一样

理论上,原始ajax请求将执行该操作,但是,我程序的jQuery部分存在问题,因此我试图将其转换为原始javascript并绕过jQuery

1 个答案:

答案 0 :(得分:3)

使用提取:

function json(response) {
  return response.json();
}

function handleErrors(response) {
  if(!response.ok) {
    throw new Error("Request failed " + response.statusText);
  }
  return response;
}

fetch("http://url.com/endpoint", {
  method: "POST",
  body: {
    myKey: "my value",
    another: "hihihi"
  }
}).then(handleErrors).then(json).then(function(data) {
  console.log(JSON.stringify(data));
}).catch(function(err){
  console.log("err" + err);
})