从调用$ .getJSON外界物体物体、外界、getJSON

由网友(涐爱沵、沵却卟爱涐°)分享简介:可能重复: Why没有这个封闭有机会获得'这个'关键字? - jQuery的 函数Class1的(){this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstei...

可能重复:   Why没有这个封闭有机会获得'这个'关键字? - jQuery的

 函数Class1的(){
    this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';

    this.f =功能(){
        $ .getJSON(this.url,函数(){
            执行console.log(this.url);
        });
    }
};

VAR OBJ =新1级();
obj.f();
 

除了打印网址的

obj.f()打印不确定到控制台。为什么会出现这种情况,我能做些什么,以prevent这种行为?

解决方案

在你的Ajax回调,将是jqXhr对象,而不是你的当前对象。你要保存在你的Ajax调用和参考价值的是的在回调:

  this.f =功能(){
    无功自我=这一点;
    $ .getJSON(this.url,函数(){
        执行console.log(self.url);
    });
}
 

python 怎么提取json中的内容

Possible Duplicate: Why doesn't this closure have access to the 'this' keyword? - jQuery

function class1() {
    this.url = 'http://en.wikiquote.org/w/api.php?action=query&format=json&prop=revisions&titles=Albert_Einstein&rvprop=content&callback=?';

    this.f = function() {
        $.getJSON(this.url, function() {
            console.log(this.url);
        });
    }
};

var obj = new class1();
obj.f();

Instead of printing the url, obj.f() prints "undefined" to the console. Why is this happening and what can I do to prevent this behaviour?

解决方案

Inside your ajax callback, this will be the jqXhr object, not your current object. You'll want to save the value of this before your ajax call, and reference that in your callback:

this.f = function() {
    var self = this;
    $.getJSON(this.url, function() {
        console.log(self.url);
    });
}

阅读全文

相关推荐

最新文章