javascript - js xml响应返回未定义
问题描述
请我需要帮助!首先,我的英语说得不太好,对不起错误
因此,我尝试使用以下代码接收 JSON 对象:
function uhttp(url){
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
console.log(xhr.response)
return xhr.response;
}
};
xhr.send();
console.log('exit')
};
但是当我像这样使用函数 https 时:
`
( ()=>{
var perso =uhttp('bd.php?table=charac')
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>')
}
})()
` perso he's undifined... 这里是 index.html 的控制台
我的印象是我们在收到响应之前退出了函数,这就是为什么函数返回 null 当然在问我的问题之前我已经做了一些研究,但没有人在我的情况下工作...... . 谢谢你的回答
解决方案
发生这种情况是因为您不是从uhttp()
函数返回值,而是从匿名函数(xhr.onload
)返回值。
为了在 AJAX 调用结束后访问此值,请使用承诺:
function uhttp(url){
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
return;
}
reject();
};
xhr.onerror = function() {
reject()
};
xhr.send();
})
}
并像这样使用它:
uhttp('bd.php?table=charac').then(function(result) {
var person = result;
for (var i = 0; i < perso.lenght; i++) {
document.getElementbyID('container').append('<ul>'+perso[i].nom+'</ul>');
}
}).catch(function() {
// Logic on error
});
推荐阅读
- c - 检查一个数字在数组中出现的次数
- c# - WPF Datagrid AlternatingRowBackground
- html - 只想让关闭按钮溢出在模态框内可见
- php - 如何使用 fscanf 在 php 中读取一行数字
- javascript - Stripe 多计划订阅 API 调用的格式数组
- database - Ecto 删除 many_to_many 连接,同时保持连接记录完整
- javascript - 具有状态(.active)的元素的getAttribute
- java - React(带有 Keycloak 的 CORS):没有设置标头或设置了两次标头,没有 OPTIONS 调用但 HTTP 状态(已取消)
- vue.js - 如何在 vue 子组件中使用 $refs 来转移焦点?
- python - 如何使用 NiBabel (Python) 预处理 NIfTI 数据格式