2017-02-26 4 views
0

http://www.serveraddress.com/api/users/1이 유효하며 값이 올바른 JSON 형식입니다.REST API에 대한 GET 요청

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이 올바르지 않습니까? 함수가 요구하더라도 전송되기 전에 response를 (비어있는) 반환

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 무엇

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)); });
? 나는 거기에 오류가있는 것 같아요. – Psi

+0

@Psi OP를 편집하여 JSON을 포함 시켰습니다. 유효한 JSON이라고 말한 JSON 포맷터를 확인했습니다. – falafel

+0

브라우저 도구 또는 Fiddler에서 응답을 확인하십시오. 실제로 JSON을 응답으로 받고 있는지 확인하십시오. – JLRishe

답변

1

XMLHttpRequest의 비동기이므로.
가 호출되는 콜백 함수를 요청이 완료되면에서 responseText를 얻을 사용하는 경우 이벤트의 load 이벤트가 발생합니다 :

관련 문제