internet explorer 9 & javascript variable scoping issue

瘦欲@ 提交于 2019-12-11 08:17:34

问题


this code works in Chrome & Firefox but not in IE9 ... need some hints ...

var obj = {
    data: [],

    json: function() {
        var self = this;
        $.getJSON("highscore.json", function(resp) {
            self.data = resp.splice(0);
        });
    }
};

Update:

thx for your help ...

it was an issue from the ie9, ie has thrown the error code "c00ce56e" - it's an issue with charset. i'll try another header in the php scripts ...

thx @ all


回答1:


Your code looks fine to me, other than that data won't be populated until the json request is done, which is NOT instant because ajax is asynchronous.

obj.json();
alert(obj.data); // []
setTimeout(function(){
    alert(obj.data); // ["foo","bar","foobar"]
},5000);

Update
I suggest adding a property to your object called request, and store the $.getJSON request in it. At that point it doesn't make sense to store the data directly on the object because you can always get it from the request.

var obj = {
    request: {done:$.noop,fail:$.noop,always:$.noop},

    json: function() {
        this.request = $.getJSON("highscore.json");
    }
};
obj.json();
// you can run the following as many times as you need to use the data.
obj.request.done(function(data){
    alert(data.splice(0));
});

just note that in it's current form you must call .json() before you can add callbacks to the request.



来源:https://stackoverflow.com/questions/10321169/internet-explorer-9-javascript-variable-scoping-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!