http://www.serveraddress.com/api/users/1
有效且值采用正确的 JSON 格式。
JSON:
{
"id":1,
"name":"Ryan Chenkie",
"email":"ryanchenkie@gmail.com",
"battles_won":0,
"created_at":"2017-02-25 19:20:58",
"updated_at":"2017-02-25 19:20:58",
"blobs":[
{
"id":1,
"name":"Blob 1",
"type":"type A",
"color":"red",
"alive":1,
"level":1,
"exercise_level":-302,
"cleanliness_level":-302,
"health_level":-302,
"owner_id":1,
"created_at":"2017-02-25 19:20:58",
"updated_at":"2017-02-26 01:23:05"
},
{
"id":5,
"name":"Blob 5",
"type":"type C",
"color":"blue",
"alive":1,
"level":1,
"exercise_level":-302,
"cleanliness_level":-302,
"health_level":-302,
"owner_id":1,
"created_at":"2017-02-25 19:20:58",
"updated_at":"2017-02-26 01:23:05"
}
]
}
当我尝试运行 getUser() 时,出现SyntaxError: JSON.parse: Unknown end of data at line 1 column 1 of the JSON data
。
我的代码有什么问题吗?我的 setRequestHeader
不正确吗?
getUser(1);
function getUser(userId) {
var usersUrl = "http://www.serveraddress.com/api/users/";
var params = userId;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", usersUrl + params, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
var response = JSON.parse(xhttp.responseText);
return response;
}
最佳答案
由于 xmlhttprequest 是异步的,因此该函数在发送请求之前就会返回响应
(为空)。
要在请求完成后获取响应文本,请使用在事件的 load
事件触发时调用的回调函数:
function getUser(userId, callback) {
var usersUrl = "http://www.serveraddress.com/api/users/";
var params = userId;
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', callback);
xhttp.addEventListener('error', () => console.log("Request to "+usersUrl+params+" failed"));
xhttp.open("GET", usersUrl + params, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send();
}
getUser(1, function() {
console.log(JSON.parse(this.responseText));
});
关于javascript - 向 REST API 发出 GET 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42464157/