我已阅读了一些StackOverflow帖子,使用了它,但仍无法获得我想要的内容。无法从XMLHttpRequest获取JSON输出
我只是想从谷歌的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是否正确?
另外值得一提的是,我使用跨源资源共享(CORS),因为我无法从本地IP访问域。
- 编辑 - 菲尔认为这是一个无法从异步返回响应的问题,但它错了,我试过使用Ajax,XMLHttpRequest,现在使用CORS,重复记法是不正确的,请删除它。
获取选项而不是XMLHttprequest? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – mkaatman
Fetch没有做这份工作@mkaatman –