如何在onreadystatechange函数之外访问XMLHttpRequest值

时间:2019-03-06 11:58:22

标签: javascript json xmlhttprequest var scoping

我有一个.php文件,它输出一个json数据,它可以完美完成,并且我得到以下结果:

./test 1 2 3 << end
Monos(1,2)
Monos(6)
end

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

[
{
    "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"
}
]

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

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();

有人可以帮助我至少提取联系人变量中的内容,以便在代码内的其他地方使用它吗?

2 个答案:

答案 0 :(得分:1)

您可以AsyncStorage 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;
}]);

答案 1 :(得分:0)

为您的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

   }
};