开发者

Populate Object using Ajax and Jquery

开发者 https://www.devze.com 2023-04-09 08:16 出处:网络
As the title says, I\'m trying to populate the properties of an object using jQuery-Ajax. I\'ve been trying to find the right way to do it for hours, but couldn\'t make it work...

As the title says, I'm trying to populate the properties of an object using jQuery-Ajax. I've been trying to find the right way to do it for hours, but couldn't make it work...

This is my code:

function Persona(){
    this.nombre;
    this.apellido;
    this.buscarNombre= function(callback){
    $.get("nombre.php", function(datos){
        datos = eval("(" + datos + ")");
        this.nombre = datos.nombre;
        this.apellido = datos.apellido;
        alert(this.nombre);
      })
    };
}

$(document).ready(function(){
       var pp = new Persona();
       alert(pp.nombre);

}

I think the problem is the scope of the function that retrieves the data 开发者_JS百科from the server it's different from the scope of the object, but I don't realize how to pass the data from one place to the other...

The data is arriving perfectly from the web server... I used FireBug to be sure...

Thanks in advance!


if you replace alert(pp.nombre); with pp.buscarNombre();. You will get the desired results. And your this reference is wrong:

function Persona(){
    var self = this;    
    this.nombre;
    this.apellido;

    this.buscarNombre= function(callback){
        $.get("nombre.php", function(datos){
            datos = eval("(" + datos + ")");
            self.nombre = datos.nombre;
            self.apellido = datos.apellido;
            alert(self.nombre);
        })
    }
}

$(document).ready(function(){
       var pp = new Persona();
       pp.buscarNombre();    
}
0

精彩评论

暂无评论...
验证码 换一张
取 消