javascript函数返回一个对象,但它没有,变量在xhr.onload函数外被销毁

时间:2018-02-13 19:04:46

标签: javascript

这可能会多次讨论。但只是为了让这个想法变得清晰。我希望我的函数返回一个对象。但是我编写代码的方式,它不会返回对象。我尝试了其他方法。但是当涉及到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));

3 个答案:

答案 0 :(得分:2)

试试这个..

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

答案 1 :(得分:0)

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);
        var obj =new pobj(data.imagefile,data.name,data.price);

        }

    }

    xhr.send();
    return obj ;
}
console.log(hhtprequest(9));

答案 2 :(得分:-1)

new pobj(data.imagefile,data.name,data.price);

您需要在var中分配此对象,然后返回该var。