Javascript to return an object, but it is not, the get destroy variable is outside the xhr.onload function

this can be discussed several times. but just to understand this idea. I want my function to return an object. but as I wrote the code, it does not return an object. I tried other ways. but the variable becomes destroyed when it goes beyond the xhr.onload function. please help me understand the problem

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));
+4
source share
3 answers

Try it.

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();
}
+2
source
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));
0
source
new pobj(data.imagefile,data.name,data.price);

You need to assign this object to var and then return this var.

-1
source

Source: https://habr.com/ru/post/1693594/


All Articles