【问题标题】:How to access XMLHttpRequest values outside the onreadystatechange function [duplicate]如何在 onreadystatechange 函数之外访问 XMLHttpRequest 值[重复]
【发布时间】:2019-07-28 02:09:15
【问题描述】:

我有一个输出 json 数据的 .php 文件,它做得很好,我得到了这个结果:

[
{
    "name": "ADMINISTRATOR",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "GUEST",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "KRBTGT",
    "email": "",
    "first_name": "",
    "last_name": ""
},
{
    "name": "DIMERS",
    "email": "",
    "first_name": "Dimers",
    "last_name": "David"
}
]

我还有一个 .js 文件,它使用 XMLHttpRequest 调用这个结果,如下所示:

function loadDoc() {
 var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) 
    {

        var contact = JSON.parse(this.responseText);

              for (var i = 0; i < contact.length; i++) 
            {
                var contacts = {name: contact[i].name, email: contact[i].email, 
                 Govphone: contact[i].first_name, phone: contact[i].last_name};

                console.log(contacts);

            }


       }
    };
  xhttp.open("GET", "js/contalist.php", true);

  xhttp.send();

  }

  loadDoc();

在控制台中,我可以获取联系人。但我需要将响应中的值分配给调用之外的变量,就像这样

 .factory('ContactService', [function () {
    var factory = {};

    factory.getContacts = function (response) {

    var contactsList=contacts;
    return contactsList;

   };

   return factory;
  }]);

有人可以帮助我了解如何至少提取联系人变量中的内容,以便我可以在代码中的其他位置使用它吗?

【问题讨论】:

  • 请将this.responseText 的输出添加到问题中。

标签: javascript json xmlhttprequest var scoping


【解决方案1】:

您可以push responseText 并在范围内的其他地方使用它。

var theContacts=[];
function loadDoc() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            theContacts.push(this.responseText);
        }
        xhttp.open("GET", "js/contalist.php", true);
        xhttp.send();
    }
}

loadDoc();


.factory('ContactService', [function() {
    var factory = {};

    factory.getContacts = function(response) {

        var contactsList=theContacts;
        return contactsList;
    };

    return factory;
}]);

要得到一个扁平化的数组:

theContacts.flat();

【讨论】:

  • console.log(thecontacts);
  • @DimersDavid 查看更新。
  • 非常感谢,到目前为止这个对我有用,但是输出带有一对额外的“[]”我如何删除它们?
  • 我已经尝试过了,但我没有得到任何结果。当我尝试控制推送的数据时,我得到一个 Uncaught TypeError: Cannot read property 'push' of undefined at XMLHttpRequest.xhttp.onreadystatechange
  • @DimersDavid 我的错,忽略尝试console.log(theContacts.flat())
【解决方案2】:

为您的factory.getContacts 使用一个全局函数,由于它是一个全局函数,您可以在您的onreadystatechange 中使用它。

var getContacts = function(contacts) {
  // do whatever you want with contacts which is array
}

// in your factory service
.factory('ContactService', [function () {
  var factory = {};

  factory.getContacts = getContacts;

  return factory;
}]);

// in your XHR request
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) 
{

    var contact = JSON.parse(this.responseText);
    var contacts = [] // init your array to store contacts
    for (var i = 0; i < contact.length; i++) {
        // push the contact to array
        contacts.push({name: contact[i].name, email: contact[i].email, Govphone: contact[i].first_name, phone: contact[i].last_name});
    }

    getContacts(contacts) // call the same getContacts function

   }
};

【讨论】:

  • 我试过了,但我收到一个错误“未定义联系人”。
  • 错误发生在哪里?你应该检查你是否在作用域中定义了变量或者变量名是否正确。
  • 我通过使用 @Olayinka 提供的“推送”使其工作。但是,输出带有一对额外的“[]”关于如何删除它们的任何想法?
  • 因为您的 responseText 是一个数组,因此当您推送到也是一个数组的 theContacts 时,您会得到嵌套数组。要跳过额外的[],只需重用将responseText 解析为json 的代码,然后使用concat 而不是push
  • 我终于让它工作了,三个月前,我才回来!问题是我调用的是整个数组而不是调用它的内容!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 1970-01-01
  • 2020-12-18
  • 1970-01-01
  • 2017-05-24
  • 2020-02-24
相关资源
最近更新 更多