【问题标题】:Load JSON data into jQuery component将 JSON 数据加载到 jQuery 组件中
【发布时间】:2015-07-04 06:17:47
【问题描述】:

我想在网页上显示来自外部 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。

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

在更改 html 代码以从 Web 访问文件时,我收到 Cross-Origin 错误(这发生在 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>

有人可以帮我解决吗?

我确信这一定是一些语法错误,但我无法弄清楚! :(

【问题讨论】:

    标签: jquery html json jsonp


    【解决方案1】:

    使用$.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;
    });
    

    对于跨域错误,在$.getJSON 的网址中添加callback=? GET 参数。

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

    参考:

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

    jquery loop on Json data using $.each

    jQuery AJAX cross domain

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-14
        • 1970-01-01
        • 1970-01-01
        • 2017-06-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多