[英]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.