【问题标题】:Reading JSON Response with Javascript - Problem使用 Javascript 读取 JSON 响应 - 问题
【发布时间】:2019-02-26 01:46:26
【问题描述】:

我正在使用 JSON 和 post 方法向服务器发送数据,但我无法读取来自服务器的响应。这是我的代码:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://staging.smartenupcs.com/api/v1/licenses/create", true);
xhr.setRequestHeader("Smartenup-API-KEY", "webflow.c407d56c5ab23115af0075+DzDMrMtWZENCoct9Pa7DUA54mIgP8c9o");
var jsonStr = JSON.stringify({
  "first_name": "Bla",
  "last_name": "Blabla",
  "email": "bla@gmail.com",
  "product_name": "webflow_essentials",
  "order_id": 21811,
  "voucher": null

});
xhr.send(jsonStr);

xhr.onreadystatechange = function() {
  if (xhr.readyState == 4 && xhr.status == 200) {
    var myObj = JSON.parse(xhr.responseText);
    alert(myObj);
  }
};

我尝试了很多选择,但没有成功。

希望有人能帮忙,先谢谢了

【问题讨论】:

  • 你试过检查什么是“xhr.status”吗?可能不是 200?
  • 使用浏览器调试工具检查正在进行的网络调用,看看是否得到了预期的响应。

标签: javascript json xmlhttprequest


【解决方案1】:

代码没有问题。

问题在于跨域请求。您似乎从 staging.smartenupcs.com 以外的域访问 API,很可能是 localhost。

只需将跨域标头添加到服务器即可。

PS:当您的前端代码和 api 托管在同一个域上时,它可以在没有跨域标头的情况下工作。

【讨论】:

    【解决方案2】:

    请在服务器端检查Access-Control-Allow-Origin 标头。还要检查该 api/action 的 OPTIONS 预检请求。之后检查 api 响应状态和您的响应检查条件。

    【讨论】:

      【解决方案3】:

      我建议使用 fetch API 而不是 XMLHttpRequest 对象。

      function postData(url = `UR_URL_HERE`, data = {}) {
        // Default options are marked with *
          return fetch(url, {
              method: "POST", // *GET, POST, PUT, DELETE, etc.
              mode: "cors", // no-cors, cors, *same-origin
              cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
              credentials: "same-origin", // include, *same-origin, omit
              headers: {
                  "Content-Type": "application/json",
                  // "Content-Type": "application/x-www-form-urlencoded",
              },
              redirect: "follow", // manual, *follow, error
              referrer: "no-referrer", // no-referrer, *client
              body: JSON.stringify(data), // body data type must match "Content-Type" header
          })
          .then(response => response.json()); // parses response to JSON
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-18
        • 2014-03-13
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        • 1970-01-01
        • 1970-01-01
        • 2017-04-02
        相关资源
        最近更新 更多