2017-02-26 164 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)); 
 
});