无法从XMLHttpRequest

时间:2017-06-07 01:22:16

标签: javascript json

我已经阅读了一些StackOverflow帖子,谷歌搜索但仍然无法获得我想要的内容。

我只是想从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);

我明白了:

enter image description here

当我这样做时:

JSON.parse(data.responseText);

我明白了:

  

未捕获DOMException:无法从中读取'responseText'属性   'XMLHttpRequest':只有对象的值才能访问该值   'responseType'是''或'text'('json')。

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

如何正确地从XMLHttpRequest获取JSON?

另外值得一提的是,我正在使用跨源资源共享(CORS),因为我无法从本地IP访问域。

- Edit-- Phil认为这是一个无法从异步中返回响应的问题,但是它错了,我尝试过使用Ajax,XMLHttpRequest并且现在使用CORS,重复的表示法不正确,请将其删除。

1 个答案:

答案 0 :(得分:0)

此行为is documented on MDN;

  

如果responseType设置为空字符串或“text”以外的任何值,则访问responseText将抛出InvalidStateError异常。

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

除此之外,您还需要将AJAX请求视为异步,而不是同步。有关详细信息,请参阅How do I return the response from an asynchronous call?

最终,你最终会得到类似的东西;

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/en-US/docs/Web/API/XMLHttpRequest/response。相反,更常见的是将responseType保留为text,将人JSON.parse()保留为responseText属性。

相关问题