这可能会被讨论多次。但只是为了让这个想法清楚。我希望我的函数返回一个对象。但是我写代码的方式,它不返回对象。我尝试了其他方法。但是当涉及到 xhr.onload 函数之外时,变量会被销毁。请帮助我理解问题
function hhtprequest(id)
{
var pobj = function(image,name,price){
this.image = image;
this.name = name;
this.price = price;
}
var xhr = new XMLHttpRequest();
xhr.open("GET","ajax/productinfforsell.php?pid="+id,true);
xhr.onload = function(){
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.response);
new pobj(data.imagefile,data.name,data.price);
}
}
xhr.send();
return pobj;
}
console.log(hhtprequest(9));
最佳答案
试试这个..
var pobj = {};
function handleData(obj){
console.log(JSON.stringify(obj));
}
function hhtprequest(id)
{
var xhr = new XMLHttpRequest();
xhr.open("GET","ajax/productinfforsell.php?pid="+id,true);
xhr.onload = function(){
if (this.readyState === 4 && this.status === 200) {
var data = JSON.parse(this.response);
pobj.image = data.imagefile;
pobj.name = data.name;
pobj.price = data.price;
handleData(pobj);
}
}
xhr.send();
}
关于javascript函数返回一个对象,但它没有,变量在xhr.onload函数之外被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48773861/