我有一个简单的 REST API,它在端点 .../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('');
}
关于javascript - XMLHttpRequest - 当 REST API 返回 JSON 对象而不是对象数组时,我遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718079/