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: unexpected 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;
}
答案 0 :(得分:1)
因为xmlhttprequest是异步的,所以在请求发送之前,函数返回response
(为空)。
要在请求完成后获取responseText,请使用在事件的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));
});