简体   繁体   中英

Call a rest WS and get: SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

I called a rest WS from my html page and I wanna get the json response:

I tried the following code:

  if (window.XMLHttpRequest){ xmlhttpp=new XMLHttpRequest();
  }else{
  xmlhttpp=new ActiveXObject("Microsoft.XMLHTTP"); 
  }
  xmlhttpp.open("GET","http://localhost:8080/myApp/services/userService/getUser/1");
  xmlhttpp.send();

  var json = xmlhttpp.responseText,
  obj = JSON.parse(json);
  alert('json'+obj.email);

But I get thar error:

SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

NB: This ws returns:

{"active":"true","email":"USER1@gmail.com","id":"1","userName":"USER1"}

The reason is that as of when you tried to parse it, json ( xmlhttpp.responseText ) was blank. XHR calls are (by default) asynchronous . send starts the call, but then your code continues while the call is happening.

To use the result, you use a readystatechange handler:

if (window.XMLHttpRequest) {
    xmlhttpp = new XMLHttpRequest();
} else {
    xmlhttpp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpp.onreadystatechange = function () {
    var json, obj;
    if (xmlhttpp.readyState === 4) {
        if (xmlhttpp.status === 200) {
            json = xmlhttpp.responseText;
            obj = JSON.parse(json);
            alert('json' + obj.email);
        } else {
            alert('the call failed');
        }
    }
};
xmlhttpp.open("GET", "http://localhost:8080/myApp/services/userService/getUser/1");

xmlhttpp.send();
// ...and code here runs **before** the call completes...

readyState 4 is "done", and then we check the HTTP status code of the result (200 = all is good).


While it's technically possible (for now) to make XHR work synchronously ( send doesn't return until the call is complete), it makes for a poor user experience, locking up the UI of the browser. So I haven't shown it here, but if you look at the XMLHttpRequest documentation , it's there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM