jQuery Ajax和对象字段 [英] JQuery Ajax and Object field

查看:87
本文介绍了jQuery Ajax和对象字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

MyObject = function(){
    this.field = null;

    this.build = function(){
        var my_url = "...";
        var my_data = "...";
        $.get(my_url, my_data, function(result){
           this.field = result;
        });
    }

    this.get = function(){
        return this.field;
    }
}

object = new MyObject();
object.build();
my_result = object.get() 

my_result现在是null,因为执行内部函数时this不是我的对象.
那么,如何设置this.field与返回值$.get?

my_result now is null because when the inner function is executed this is not my object.
So, how can i set this.field with the $.get returned value???

推荐答案

在构造函数的顶部,执行以下操作:

In the top of your constructor, do:

var self = this;

这将创建一个引用当前对象的新范围变量.

this creates a new scoped variable that refers to the current object.

然后在AJAX回调中执行:

Then in the AJAX call back do:

self.field = result;

这篇关于jQuery Ajax和对象字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆