2017-02-26 160 views
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; 

}

+0

什麼是導致JSON?我想這裏有一個錯誤。 – Psi

+0

@Psi我編輯了OP來包含JSON。我檢查了一個JSON格式化程序,它說它是有效的JSON。 – falafel

+0

檢查瀏覽器工具或提琴手的響應。確保它實際上獲得了該JSON作爲迴應。 – JLRishe

回答

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)); 
 
});