我想使用XMLHttpRequest调用get rest api,但是我得到了错误-
“未捕获SyntaxError: JSON输入意外结束”。
rest api json响应数据
{
"timestamp": "2018-06-08T16:52:50.509Z",
"dataFrame": "AQAAKCoAAQgFKgABBg==",
"fcnt": 825,
"freq": 865572000,
"port": 2,
"rssi": -115,
"snr": -16,
"sf_used": 12,
"id": 1528476770509,
"dr_used": "SF12BW125",
"decrypted": true
}
代码
<script>
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
}
</script>
编辑:
代码
<script>
function userAction() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
var dataFrame = response.dataFrame;
/** code that handles the response **/
}
};
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2VybmVsc==");
xhttp.send();
</script>
HTML
<button type="submit" onclick="userAction()">Search</button>
<h1 id="data"></h1>
发布于 2018-06-09 02:13:20
您应该侦听请求的XMLHTTPRequest.onreadystatechange
事件,以便只在请求完成后才解析结果:
functio userAction() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let response = JSON.parse(xhttp.responseText);
document.getElementById("data").innerHTML = response.dataFrame;
}
};
xhttp.open("GET", "filename", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.send();
}
发布于 2018-06-09 02:16:51
您需要将xhttp.onreadystate属性设置为回调函数来处理各种状态,然后在收到响应时对其进行处理。
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
发布于 2018-06-09 02:21:57
在输出请求之前,您应该检查请求的状态。
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "url", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.setRequestHeader("Authorization", "Basic a2Vyb==");
xhttp.onload = function(){
if(xhttp.status ==200){
var response = JSON.parse(xhttp.responseText);
}
}
xhttp.send();
}
https://stackoverflow.com/questions/50766264
复制相似问题