将 JSON 数据加载到 jQuery 组件中

Load JSON data into jQuery component

我想在网页上显示来自外部 JSON 文件的数据。

data.json:

{"users":[
    {
        "firstName":"S",
        "lastName":"S",
        "joined": {
            "month":"January",
            "day":12,
            "year":2012
        }
    },
    {
        "firstName":"S",
        "lastName":"P",
        "joined": {
            "month":"April",
            "day":28,
            "year":2010
        }
    }
 ]}

html代码如下:

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
  $.getJSON('data.json', function(data) {
        var output="<ul>";
        for (var i in data.users) {
            output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>hello world
</html>

当我 运行 此代码在 chrome 上时,我收到以下错误:

XMLHttpRequest 无法加载 file:///C:/Users/.../jsonJquery/data.json。仅协议方案支持跨源请求:http、data、chrome、chrome-extension、https、chrome-extension-resource.

但是,相同的代码 运行s 在 Firefox 上。我无法弄清楚在两个不同的浏览器上使用相同的代码到底出了什么问题。

在更改 html 代码以从 Web 访问文件时,我收到跨源错误(这在 firefox 和 chrome 上都会发生)

    <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Sample</title>
</head>
<body>
    <div id="placeholder"></div>
    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <script>
  $.getJSON('www.someDomain.com/data.json', function(data) {
        var output="<ul>";
        for (var i in data.users) {
            output+="<li>" + data.users[i].firstName + " " + data.users[i].lastName + "--" + data.users[i].joined.month+"</li>";
        }

        output+="</ul>";
        document.getElementById("placeholder").innerHTML=output;
  });
    </script>
</body>hello world
</html>

我的问题是这些错误的原因是什么?有没有其他方法可以访问远程放置的数据?

更新:JSONP 实现工作正常!谢谢!

我要实现的是动态添加手风琴组(通过从 JSON 文件中读取)。但我不断收到错误消息:

'Uncaught TypeError: $(...).accordion is not a function'

下面是我的代码:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<script type="text/javascript" src="external/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="external/jquery.ui.core.min.js"></script>
<script type="text/javascript" src="external/jquery.ui.widget.min.js"></script>
<script>

(function($) {
var url = 'http://www.someDomain.com/data.json?callback=?';

$.ajax({
   type: 'GET',
    url: url,
    async: false,
    jsonpCallback: 'jsonCallback',
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
       console.dir(json.sites);
       var $bar = $( "#accordion" ).accordion();
       $bar.accordion('clearGroups');
       $.each(data, function(id, group){
        $bar.accordion('addGroup', group);
        });
    },
    error: function(e) {
       console.log(e.message);
    }
});

})(jQuery);

</script>
<style type="text/css">
.widget
{
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div id="accordion" class="widget"></div>
</body>
</html>

有人可以帮我解决一下吗?

我确定这一定是语法错误,但我无法弄明白! :(

对跨域请求使用withCredentials选项,这将有助于避免跨域错误:

$.ajax({
    url: "http://www.someDomain.com/data.json",
    type: "GET",
    dataType: 'json',
    xhrFields: {
         withCredentials: true
    }
}.done(function() {
   // your code here
});

使用$.each()操作json数据:

$.getJSON('data.json', function(data) {
    var output = "<ul>";
    $.each(data.users, function(i, item) {
        output += '<li>' +
            item.firstName + ' ' +
            item.lastName + ' ' +
            item.joined.month +
            '</li>'
    });
    output += "</ul>";
    document.getElementById("placeholder").innerHTML = output;
});

同样对于跨源错误,将 callback=? GET 参数添加到 $.getJSON 中的 url。

但一般来说,您必须实施 JSONP 才能正确完成。

参考文献:

http://www.w3schools.com/jquery/ajax_getjson.asp

jquery loop on Json data using $.each

jQuery AJAX cross domain