简体   繁体   English

无法从XMLHttpRequest获取JSON输出

[英]Unable to get JSON output from XMLHttpRequest

I've read a few StackOverflow posts, googled it but still can't get what I want. 我已经阅读了一些StackOverflow帖子,在Google上进行了搜索,但仍然无法获得我想要的东西。

I simply want to get a JSON from Google's API and import it to a variable so I can filter it the way I want, the following code is what I have so far: 我只是想从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>

When I do: 当我做:

console.log(data);

I get: 我得到:

在此处输入图片说明

When I do: 当我做:

JSON.parse(data.responseText);

I get: 我得到:

Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json'). 未捕获的DOMException:无法从“ XMLHttpRequest”读取“ responseText”属性:仅当对象的“ responseType”为“”或“ text”(为“ json”)时,才可以访问该值。

What should I get on console.log: https://pastebin.com/4H7MAMcM 我应该在console.log上获得什么: https : //pastebin.com/4H7MAMcM

How can I get the JSON from XMLHttpRequest correctly? 如何从XMLHttpRequest中正确获取JSON?

Also worth mentioning, I'm using Cross-Origin Resource Sharing (CORS) because I couldn't access the domain from my local IP. 同样值得一提的是,由于无法从本地IP访问域,因此我正在使用跨域资源共享(CORS)。

--Edit-- Phil thought this was a matter of not being able to return response from a asynchronous, but its wrong, I've tried using Ajax, XMLHttpRequest and now using CORS, the duplicate notation was incorrect, please remove it. -编辑-菲尔(Phil)认为这是无法从异步返回响应的问题,但是它是错误的,我尝试使用Ajax,XMLHttpRequest和现在使用的CORS,重复符号不正确,请删除它。

This behaviour is documented on MDN ; 此行为记录在MDN上

If responseType is set to anything other than the empty string or "text", accessing responseText will throw InvalidStateError exception. 如果responseType设置为空字符串或“文本”以外的任何其他内容,则访问responseText将引发InvalidStateError异常。

Instead, you need to use the response property. 相反,您需要使用response属性。 Since you specified json as the responseType , response will be a JavaScript object (no need to JSON.parse it). 由于您将json指定为responseType ,因此response将是一个JavaScript对象(无需JSON.parse )。

Aside from this, you'll also need to treat the AJAX request as asynchronous, rather than synchronous. 除此之外,您还需要将AJAX请求视为异步而不是同步。 For more info on that, see How do I return the response from an asynchronous call? 有关更多信息,请参阅如何返回异步调用的响应? .

Eventually, you should end up with something like; 最终,您应该得到类似的结果。

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://jsfiddle.net/ez3xt6ys/

However , the browser support seems patchy for this at best; 但是 ,浏览器支持充其量似乎很少。 https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/response . https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/response Instead, it is more common to see the responseType being left as text , and for people to JSON.parse() the responseText property. 相反,更常见的是将responseType保留为text ,对于人们来说,使用JSON.parse()responseText属性。

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

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