繁体   English   中英

无法从XMLHttpRequest获取JSON输出

[英]Unable to get JSON output from XMLHttpRequest

我已经阅读了一些StackOverflow帖子,在Google上进行了搜索,但仍然无法获得我想要的东西。

我只是想从Google的API中获取一个JSON并将其导入一个变量,以便我可以按自己的方式进行过滤,到目前为止,以下代码是我所拥有的:

<!DOCTYPE html>
<html>
<body>

Term: <input type="text" id="field1" value="Mc Donalds in New York"><br>

<button onclick="myFunction()">Search</button>

<script>
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
    xhr.responseType = 'json';
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
    xhr.responseType = 'json';
  } else {
    xhr = null;
  }
  return xhr;
}

function myFunction() {
    var termo = document.getElementById("field1").value;
    var URL = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="+termo.replace(" ","+")+"&key=HIDDEN_KEY";
    var data = createCORSRequest('GET',URL);
    if (!data) {
      throw new Error('CORS not supported');
    }
}
</script>

</body>
</html>

当我做:

console.log(data);

我得到:

在此处输入图片说明

当我做:

JSON.parse(data.responseText);

我得到:

未捕获的DOMException:无法从“ XMLHttpRequest”读取“ responseText”属性:仅当对象的“ responseType”为“”或“ text”(为“ json”)时,才可以访问该值。

我应该在console.log上获得什么: https : //pastebin.com/4H7MAMcM

如何从XMLHttpRequest中正确获取JSON?

同样值得一提的是,由于无法从本地IP访问域,因此我正在使用跨域资源共享(CORS)。

-编辑-菲尔(Phil)认为这是无法从异步返回响应的问题,但是它是错误的,我尝试使用Ajax,XMLHttpRequest和现在使用的CORS,重复符号不正确,请删除它。

此行为记录在MDN上

如果responseType设置为空字符串或“文本”以外的任何其他内容,则访问responseText将引发InvalidStateError异常。

相反,您需要使用response属性。 由于您将json指定为responseType ,因此response将是一个JavaScript对象(无需JSON.parse )。

除此之外,您还需要将AJAX请求视为异步而不是同步。 有关更多信息,请参阅如何返回异步调用的响应?

最终,您应该得到类似的结果。

function createCORSRequest(method, url, cb) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    xhr.open(method, url, true);
    xhr.responseType = 'json';
    xhr.onreadystatechange = function () {
        if (this.readyState === 4) {
        cb(this.response);
      }
    }
    xhr.send(null);
  } else if (typeof XDomainRequest != "undefined") {
    xhr = new XDomainRequest();
    xhr.open(method, url);
    xhr.responseType = 'json';
  } else {
    xhr = null;
  }
  return xhr;
}

createCORSRequest('POST', '/echo/json/', function (response) {
    console.log(response);
});

https://jsfiddle.net/ez3xt6ys/

但是 ,浏览器支持充其量似乎很少。 https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/response 相反,更常见的是将responseType保留为text ,对于人们来说,使用JSON.parse()responseText属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM