我正在尝试构建一个基本的React应用程序,该应用程序可以访问API以获取引号。 “ GET”请求返回一个字符串,但是,当我尝试将字符串解析为JSON时,就是收到错误。
这是我发出请求的功能:
const httpCallout = () => {
const Http = new XMLHttpRequest();
const endpoint = "http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1";
Http.open("GET", endpoint, true);
Http.send();
let reply = "";
Http.onreadystatechange = (e) =>{
console.log(JSON.parse(Http.response));
//console.log(Http.response);
}
return reply;
}
以及来自服务器的解析响应:
[
{
"ID": 1286,
"title": "Adrian Shaughnessy",
"content": "<p>Graphic design has been likened to a wine glass. When we drink wine we barely notice the glass it’s served in. It wouldn’t be true to say that we don’t care what glass we drink out of – we wouldn’t choose to drink a rare vintage out of a Tupperware mug, for example – but it’s the wine that matters, not the vessel it comes in. </p>\n",
"link": "https://quotesondesign.com/adrian-shaughnessy/",
"custom_meta": {
"Source": "<a href=\"http://observatory.designobserver.com/entry.html?entry=7257\">transcript</a>"
}
}
]
我也在寻找非jQuery响应。同样,控制台抛出的全部错误是:SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
,并在第console.log(JSON.parse(Http.response));
行给出错误
答案 0 :(得分:1)
您的方法中有几处错误。
1.-发出“ http”请求是不安全的,因为浏览器会将其标记为不安全,而是使用https。
2.-您收到的答案无效,无法创建JSON.parse。
我推荐这段更简洁的代码:)
Private Sub PA_Change()
Me.object.Visible = PA.Value ' TODO: give 'object' an actual name
End Sub
答案 1 :(得分:0)
阅读onreadystatechange
的文档:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
仅当readyState设置为4时,该响应才可用,但多次执行回调(在响应到达之前)。
要解决此问题,请确保仅在response
实际使用时对其进行处理。
或者,您可能更喜欢使用不直观的新API在浏览器中执行HTTP请求:fetch()
。