我有一个输出 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;
}]);
有人可以帮助我如何至少提取联系人变量中的内容,以便我可以在代码中的其他位置使用它吗?
最佳答案
您可以推送
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();
关于javascript - 如何在 onreadystatechange 函数之外访问 XMLHttpRequest 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55022617/