gpt4 book ai didi

javascript - JSON.parse 功能失败,在控制台中工作

转载 作者:行者123 更新时间:2023-11-30 10:30:37 24 4
gpt4 key购买 nike

我有一个简单的脚本,它执行跨站点请求并从 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com