IE中的$ .getJSON $ .each仅在刷新后才能正常工作

时间:2012-11-27 10:14:42

标签: javascript jquery json

我正在使用javascript输出图像,一切正常在FF和Chrome中工作但在IE中只在第一次加载页面时附加第一张图片,只有在刷新页面后才会附加所有图像。

输出图片的Javascript:

  $.getJSON("php/v.php?"+Math.random(),function(data){              
                $.each(data,function(l){
                        if(data[l]['s']==1){                
                             $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />");
                        }                   
                    });
        });

来自IE9 dev工具的响应来自v.php:

[{"img":"https:\/\/www.example.com\/example.jpg","s":"1"},{"img":"https:\/\/www.example.com\/example.jpg","s":"1"},{"img":"https:\/\/www.example.com\/example.jpg","s":"1"}]

所以问题应该是由每个元素而不是getJSON引起的。 在stackoverflow上发现了许多类似的问题,但没有这样的 (http://stackoverflow.com/questions/7785138/each-method-only-applies-to-first-element-in-ie,http://stackoverflow.com/questions/4664190/javascript-each-loop-over -json-only-getting-first-element)但在我的情况下,问题也出现在IE9中。

2 个答案:

答案 0 :(得分:0)

您的JSON中存在语法错误。第二个URL有两个结束“引号

答案 1 :(得分:0)

我认为您可以先在本地浏览器中进行调试,如下所示:

var data= [{},{},{}];//your data

$.each(data,function(l){
    if(data[l]['s']==1){                
        $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />");
    }                   
});

//and this way
for(var i=0,l=data.length; i<l; i++){
    if(data[l]['s']==1){                
        $("#img"+(l+1)).append("<img src='"+data[l]['img']+"' />");
    } 
}

//and the third way
for(var i=0,l=data.length; i<l; i++){
    if(data[l]['s']==1){
        var img = new Image();
        img.onload = function(){
            var id = '#img'+(l+1);
            $(id).append(this);
        }
        img.src = data[l]['img'];
    } 
}