作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个简单的脚本,它执行跨站点请求并从 GitHub 要点获取数据。来自 Github API 的数据以 JSON 字符串的形式返回。为了允许进一步修改数据,我希望将其作为 JSON 对象。
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
var tmpJSON = "";
var gistData = "";
var gistID = "5789756";
var gitAPI = "https://api.github.com/gists/"
var gistQuery = gitAPI + gistID;
function incrementGist() {
gistData = createCORSRequest('GET', gistQuery);
gistData.send();
tmpJSON = JSON.parse(gistData.response);
}
在html页面中,我有
<p><input type="button" value="Increment" OnClick="incrementGist()"></p>
如果我真的按下按钮,我得到的错误是:
Uncaught SyntaxError: Unexpected end of input
但是如果我随后打开控制台并运行它:
var crap = JSON.parse(gistData.response);
它工作得很好。这在 Firefox 和 Chrome 中都会发生。我真的不明白为什么 JSON.parse
命令在函数调用中失败,但在控制台中却没有。实际页面已设置here
最佳答案
问题是您试图在服务器响应之前读取响应。
您必须在回调中读取响应。例如:
gistData = createCORSRequest('GET', gistQuery);
gistData.onreadystatechange = function() {
if (gistData.readyState === 4) {
if (gistData.status === 200) {
tmpJSON = JSON.parse(gistData.response);
... use tmpJSON...
... which should not be called so as it is not JSON...
... maybe tmpObject ?
}
}
}
gistData.send();
关于javascript - JSON.parse 功能失败,在控制台中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17148807/
我是一名优秀的程序员,十分优秀!