簡體   English   中英

調用其余的WS並獲取:SyntaxError:JSON.parse:JSON數據第1行第1列的數據意外結束

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

我從html頁面調用了一個REST WS,我想得到json響應:

我嘗試了以下代碼:

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

但是我得到了錯誤:

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

注意:此ws返回:

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

原因是,當您嘗試解析它時, jsonxmlhttpp.responseText )為空。 XHR調用(默認情況下)是異步的 send 啟動呼叫,但是在呼叫進行期間您的代碼繼續。

要使用結果,請使用readystatechange處理程序:

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為“ done”,然后檢查結果的HTTP狀態代碼(200 =一切正常)。


盡管在技術上(目前)可以使XHR同步工作(直到調用完成才返回send ),但這會帶來糟糕的用戶體驗,從而鎖定了瀏覽器的UI。 因此,這里沒有顯示它,但是如果您查看XMLHttpRequest文檔 ,它將在那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM