开发者

javascript undefined

Why cant I access the render function when ajax returns successfully? maybe im going crazy but i've done this before.

Its telling me that this.render is not a function?

DataItem.prototype = {
    display: function () {
        $('body').append(this.name + ": " + this.getData(this.rootData, this.subData) + "<br />");
    },
    getData: function (rootData, subData) {
        $.ajax({
            type: "GET", 
            url: "json/data.js",
            data: "",
            dataType: "json",
            success: function (json){
                this.render(json);
            }
        });
    },
    render: function (json) {
        var res = [];
        for(var i=0, t; t=json.log.entries开发者_C百科[i]; i++) {
            var p = t.request.url;
            if (p!=undefined) res.push(p);
        }
        return res.length;
    }
};


The scope has changed when you try to call this.render(). I believe this contains the ajax request object instead of the DataItem object.

A simple solution is doing like this:

getData: function (rootData, subData) {
    var self = this;
    $.ajax({
        type: "GET", 
        url: "json/data.js",
        data: "",
        dataType: "json",
        success: function (json){
            self.render(json);
        }
    });
},

Edit: I was wrong, inside the success function the this variable contains the options for the ajax request, however my solution is still correct. See more in the jQuery documentation (http://docs.jquery.com/Ajax/jQuery.ajax#options)


Just to add to @adamse answer. If you want to externalize your success function instead of using an anonymous function you could use the following to pass additional parameters:

function handleSuccess(json) {
   this.self.render(json);
}

$(function() {
    $.ajax({
        type: "GET", 
        url: "json/data.js",
        data: "",
        dataType: "json",
        // pass an additional parameter to the success callback
        self: this,
        success: handleSuccess
    });
});


since the following code works (i.e "abcd" is printed), I am not sure what is the problem you are facing unless you would share more code.

<script>
    DataItem = function(){};
    DataItem.prototype = {
        display: function () {
            return 'a';
        },
        getData: function () {
            document.write(this.render());
            return this;
        },
        render: function () { return "abcd"; }
    };


    di = new DataItem();
    di.getData();

</script>
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜