首页 文章

解析我的json文件

提问于
浏览
0

我试图使用jquery解析一个json文件,但我没有得到任何数据,

我的jquery代码:

$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: 'http://anteatercycles.co.uk/xml/sensa.json',
        success: function (json) {
            var data1 = json.data[0];
            var result1 = '<h3>' + data1.merchant_category + '</h3>' + '<p>' + data1.description + '</p>' ;
            $('#description1').append(result1);
        }
    });
});

<div id="description1"></div>

提前致谢 .

编辑到下面仍然没有检索任何数据?

$(document).ready(function () {

$ .ajax({type:'GET',dataType:"json",url:'http://anteatercycles.co.uk/xml/sensa.json ', success: function (json) { json=JSON.parse(json);//parse json data var data1 = json.data[0]; var result1 = '

'data1.merchant_category'

' + '
'data1.description'
' ; $('#description1') . append(result1); }}; });

</script>   

<div id="description1"></div>

4 回答

  • 0

    添加 dataType: 'json' 作为AJAX调用的选项应该可行 . 如果你告诉jQuery它很可能是服务器不是纯文本的.533969_ .

  • 0

    使用 JSON.parse() 或设置 dataType:"json"

    success: function (json)
          {   json=JSON.parse(json);//parse json data
              var data1 = json.data[0];
              var result1 = '<h3>' + data1.merchant_category + '</h3>' +
              '<p>' + data1.description + '</p>' ;
              $('#description1').append(result1);
          }
    
  • 3

    如果你期望从你的服务得到 JSON 响应你需要给 dataType:"JSON" 然后这将自动返回一个JavaScript对象.JSON数据以严格的方式解析 . 任何格式错误的 JSON 被拒绝并抛出一个解析错误或者你是获得服务的空响应 .

  • 3

    查看服务器为该JSON发送的数据:

    %  curl -I http://anteatercycles.co.uk/xml/sensa.json
    HTTP/1.1 200 OK
    Server: Apache
    Last-Modified: Thu, 04 Sep 2014 10:41:58 GMT
    ETag: "fe1328ea-4ff3e-5023b007f6708"
    Content-Type: text/plain
    Content-Length: 327486
    Accept-Ranges: bytes
    Date: Thu, 04 Sep 2014 12:10:03 GMT
    X-Varnish: 2518742114 2518618326
    Age: 72
    Via: 1.1 varnish
    Connection: keep-alive
    

    重要的是 Content-Type . 它声称它是 text/plain 但它应该是 application/javascript .

    您应该修复服务器,以便为该文件提供正确的内容类型 .

    作为一个hacky解决方法,您可以告诉jQuery忽略内容类型并将其视为JSON .

    dataType: "json" 添加到您的ajax选项:

    $.ajax({
        type: 'GET',
        dataType: "json",
    

    此外,JSON不返回具有 data 属性的对象 . 所以访问 json.data 是没有意义的 . 你想要 json[0] .

相关问题