如何解决xmlhttprequest 返回未定义的错误或返回数据
XMLHttpRequest
有点问题。我正在按照我认为应该完成的方式设置对象,但我没有在响应属性中获取任何数据,它始终未定义。
function getApi() {
var xhr = new XMLHttpRequest();
xhr.open("GET","https://jsonplaceholder.typicode.com/posts");
//xhr.withCredentials = true;
xhr.responseType = "text/html";
// xhr.overrideMimeType("application/text");
xhr.onload = function () {
return xhr.responseText;
};
xhr.send();
}
let status = getApi();
alert(status);
解决方法
您可以使用 fetch
代替:
function getApi() {
const url = 'https://jsonplaceholder.typicode.com/posts';
return fetch(url)
.then(res => res.json())
.then(data => data)
.catch(e => e);
}
getApi().then(data => alert(JSON.stringify(data,null,2)));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。