簡體   English   中英

XMLHttpRequest - 當REST API返回JSON對象而不是對象數組時,我遇到了問題

[英]XMLHttpRequest - I have problem when REST API returns JSON object and not array of object

我有簡單的REST API,它在endpoint ... / statistics下返回一個JSON對象

我試圖在js腳本中獲取此對象,但XMLHttpRequest的響應文本為空。

我注意到當API返回JSON數組時,響應文本不為空。

這是我腳本中的js函數:

函數httpGet(theUrl){

var xmlHttp = new XMLHttpRequest();

xmlHttp.open("GET", theUrl, false); // false for synchronous
xmlHttp.send();
return xmlHttp.responseText;

}

因此,當API響應只有一個JSON對象時,xmlHttp.responseText為空。 當API響應是JSONS數組時,它可以正常工作。

var url = 'somePage.html'; //A local page

function load(url, callback) {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4) {
      callback(xhr.response);
    }
  }

  xhr.open('GET', url, true);
  xhr.send('');
}

暫無
暫無

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

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