使用promise - pure javascript发送带参数(数据)的post请求

时间:2018-01-24 14:09:26

标签: javascript php promise es6-promise

如果我使用简单的帖子xhr请求,它的工作是发送帖子参数:

var http = new XMLHttpRequest();
var url = "example url";
var params = "limit=2";
http.open("post", url);
http.onreadystatechange = function() {
    if(http.readyState == 4 && http.status == 200) {
       alert(http.responseText);
    }
}
http.send(params);

但是如果我使用带参数(数据)的promise然后我得到未定义的索引php错误,承诺我不能发送参数?或者我想念一些......

  function postAjaxCall(url, data) {
  // return a new promise.
  return new Promise(function(resolve, reject) {
    // do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('post', url);

    req.onload = function() {
      if (req.status == 200) {
      resolve(req.response);
      }
      else {
        reject(Error(req.statusText));
      }
    };

    // handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // make the request
    req.send(data);
    //same thing if i hardcode like
    //req.send("limit=2");
  });
};

我发出请求

postAjaxCall('example url', "limit=2").then(
        function(response) {
          document.getElementById('example').innerHTML = response;
        },
        function(error) {
          console.error("Failed!", error);
        });

1 个答案:

答案 0 :(得分:1)

如果您在服务器端检查请求标头,您将看到您的请求是以text / plain发送的。要使PHP将请求视为$ _POST,您需要将请求标头设置为'application / x-www-form-urlencoded',它应该在xhr.open()之后和xhr.onload之前。 https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started显示了Ajax的基本用法。

function postAjaxCall(url, data) { 
    // return a new promise. 
return new Promise(function(resolve, reject) { 
    // do the usual XHR stuff 
var req = new XMLHttpRequest();
req.open('post', url); 
//NOW WE TELL THE SERVER WHAT FORMAT OF POST REQUEST WE ARE MAKING 
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.onload = function() { 
    if (req.status == 200) { 
        resolve(req.response); 
    } else { 
        reject(Error(req.statusText)); 
        } 
    }; 
    // handle network errors 
req.onerror = function() { 
    reject(Error("Network Error")); 
}; // make the request 
req.send(data); 
    //same thing if i hardcode like //req.send("limit=2"); 
}); 
};