编程语言
首页 > 编程语言> > javascript-$.getJSON()在IE9中有效,但在Chrome和FireFox中无效,我的代码有什么问题?

javascript-$.getJSON()在IE9中有效,但在Chrome和FireFox中无效,我的代码有什么问题?

作者:互联网

我使用IE9和文本编辑器开发了一个Web应用程序.它读取一个JSON文件,然后根据该文件以及JavaScript和jQuery代码的逻辑填充一些DIV元素.在IE9下,它可以完美运行.

在Chrome下,它无法执行$.getJSON()语句,因此没有可用数据.在FireFox下,$.getJSON()语句显然可以运行(警报消息对此进行了证明),但是它什么也没读取.

JSON文件传递JSONLint.

Chrome和FireFox均未指示任何错误.

我使用来自JSON站点的JSON数据制作了一个示例文件,并通过JSONLint对其进行了验证,然后使用该文件运行了我的代码.没什么不同-Chrome仍然会忽略$.getJSON()语句.

我的代码的相关部分:

    function buildTree(centralID) {
      alert("Can we start, at least?");
     $.getJSON('sample.json', function(data) {
      alert("first success");
      $.each(data.person, function(i, xdata) {

Chrome显示第一个警报,但不显示第二个.

有任何想法吗?

解决方法:

您可以使用内置的错误功能来显示错误并进行调试.

$(document).ready(function(){ // Make sure your jQuery is inside this
$.getJSON("sample.json", function(data) {
    alert('Point 1 Reached.');
    console.log(data); // Here we log to our console
    $.each(data.feed.entry, function(i, item) {
             // Do your stuff here
        }); // End of $.each

// Here Success, Completed & Error do something. chained onto $.getJSON
        }).success(function() { alert("success"); })
          .error(function(jqXHR, textStatus, errorThrown) { // Debug the error!!
                    console.log("error " + textStatus);
                    console.log("error throw " + errorThrown);
                    console.log("incoming Text " + jqXHR.responseText);
                }) // End of .error
          .complete(function() { alert("complete"); });
        });
}); // End of DOM Ready

这应该会在firefox或chrome的控制台窗口中向您显示错误(console.log在IE中不起作用并破坏脚本).要以Firefox或chrome调出控制台窗口,请按F12.如果JSON不起作用,它将显示一个错误,您可以调试.

更新资料
还要确保此代码位于$(document).ready()中.如果以其他方式使用$.getJSON(),可能会导致跨浏览器的意外行为.

标签:cross-browser,json,javascript,jquery,jsonlint
来源: https://codeday.me/bug/20191101/1987522.html