简体   繁体   中英

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

I have simple REST API which returns one JSON object under endpoint .../statistics

I am trying to get this object in js script but response text from XMLHttpRequest is empty.

I noticed that response text is not empty when API returns arrays of JSONs.

This is my js function in script:

function httpGet(theUrl) {

var xmlHttp = new XMLHttpRequest();

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

}

So when API response is only one JSON object xmlHttp.responseText is empty. When API response is arrays of JSONS it works fine.

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('');
}

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