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

标签 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));

最佳答案

试试这个..

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/

相关文章:

javascript - Twitter Bootstrap 的 javascript Popover 看起来不对

javascript - 使用 Createjs 和 Chartjs

javascript - 每次通过 Google Instant 发出新查询时都会触发 Greasemonkey 脚本

javascript - 在 textarea 中呈现 HTML

javascript - 使用 Jasmine 测试 ajax 请求内的 Angular 范围变量

javascript - 一开始如何不启用切换类?

javascript - react JS/ES6 : Equivalence between two blocks of code

javascript - Backbone - 监听多个事件并确定触发哪个事件

JavaScript 正则表达式

javascript - 为什么我的 redux 组件中有多个容器?有什么好处?