2017-06-07 137 views
0

我已閱讀了一些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); 

我得到:

enter image description here

當我這樣做:

JSON.parse(data.responseText); 

我得到:

未捕獲拋出:DOMException:無法讀取 '的XMLHttpRequest' 的 'responseText的' 屬性:值只有當對象的 '的responseType' 是受影響''或'text'(是'json')。

我應該得到的console.log: https://pastebin.com/4H7MAMcM

如何從XMLHttpRequest的獲得JSON是否正確?

另外值得一提的是,我使用跨源資源共享(CORS),因爲我無法從本地IP訪問域。

- 編輯 - 菲爾認爲這是一個無法從異步返回響應的問題,但它錯了,我試過使用Ajax,XMLHttpRequest,現在使用CORS,重複記法是不正確的,請刪除它。

+1

獲取選項而不是XMLHttprequest? https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch – mkaatman

+0

Fetch沒有做這份工作@mkaatman –

回答

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屬性的人更爲常見。