0
http://www.serveraddress.com/api/users/1
是有效的,值是正確的JSON格式。GET請求到REST API
的JSON:
{
"id":1,
"name":"Ryan Chenkie",
"email":"[email protected]",
"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;
}
什麼是導致JSON?我想這裏有一個錯誤。 – Psi
@Psi我編輯了OP來包含JSON。我檢查了一個JSON格式化程序,它說它是有效的JSON。 – falafel
檢查瀏覽器工具或提琴手的響應。確保它實際上獲得了該JSON作爲迴應。 – JLRishe