互联网浏览器9& javascript变量作用域问题 [英] internet explorer 9 & javascript variable scoping issue

查看:93
本文介绍了互联网浏览器9& javascript变量作用域问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码可在Chrome& Firefox,但在IE9中却没有...需要一些提示...

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);
        });
    }
};

更新:

thx为您提供帮助...

thx for your help ...

这是来自ie9的问题, 即抛出了错误代码"c00ce56e"-这是字符集的问题. 我将在php脚本中尝试另一个标头...

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 @全部

推荐答案

您的代码对我来说还不错,除了在完成json请求之前,不会填充数据,因为ajax是异步的,所以这不是即时的. /p>

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);

更新
我建议向您的对象添加一个名为request的属性,并将$ .getJSON请求存储在其中.那时,将数据直接存储在对象上没有任何意义,因为您始终可以从请求中获取数据.

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));
});

请注意,在当前形式下,您必须先调用.json(),然后才能向请求中添加回调.

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

这篇关于互联网浏览器9& javascript变量作用域问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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