简体   繁体   English

XMLHttpRequest - 当REST API返回JSON对象而不是对象数组时,我遇到了问题

[英]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 我有简单的REST API,它在endpoint ... / statistics下返回一个JSON对象

I am trying to get this object in js script but response text from XMLHttpRequest is empty. 我试图在js脚本中获取此对象,但XMLHttpRequest的响应文本为空。

I noticed that response text is not empty when API returns arrays of JSONs. 我注意到当API返回JSON数组时,响应文本不为空。

This is my js function in script: 这是我脚本中的js函数:

function httpGet(theUrl) { 函数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. 因此,当API响应只有一个JSON对象时,xmlHttp.responseText为空。 When API response is arrays of JSONS it works fine. 当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