首页 > 解决方案 > 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 当然在问我的问题之前我已经做了一些研究,但没有人在我的情况下工作...... . 谢谢你的回答

标签: javascriptxmlnullreturnresponse

解决方案


发生这种情况是因为您不是从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
  });

推荐阅读