2017-06-07 142 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属性的人更为常见。