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

How to access XMLHttpRequest values outside the onreadystatechange function

我有一个 .php 文件输出 json 数据,它完美地完成了我得到的结果:

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

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

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

   }
};

您可以 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();