不能用$ .ajax()方法解析JSON对象

时间:2014-04-03 22:04:36

标签: javascript jquery ajax json

我正在尝试使用$.ajax()方法解析JSON对象(不存储在文件上),但它不是函数!能不能让我知道我做错了什么?

var painting = [
        {
        "title": "Boardwalk 5",
        "artist": "Arnie Palmer",
        "image": "ap1.jpg",
        "price": 850
        },
        {
        "title": "A Lasting Piece",
        "artist": "Arnie Palmer",
        "image": "ap2.jpg",
        "price": 450
        },
        {
        "title": "Surf at High Tide",
        "artist": "Arnie Palmer",
        "image": "ap3.jpg",
        "price": 950
        },
        {
        "title": "The Games We Play",
        "artist": "Arnie Palmer",
        "image": "ap4.jpg",
        "price": 850
        }
      ];
$(document).ready(function () {
$.ajax({
    type: 'GET',
    url: 'painting',
    dataType: 'json',
    success: jsonParser
});

});

function jsonParser(json) {
    $.getJSON(painting, function(data){
        $.each(painting, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('<div class="painting"><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
        });
    });
}

2 个答案:

答案 0 :(得分:2)

为什么需要.ajax来解析变量中的json?

你有没有尝试过这个:

$.each(painting, function(k,v){
  var title = v.title;
  var price = v.price;
  $('#container').append('<div class="painting"><br/><div class="title">' + title + '<br/>$' + price + '</div></div>')
});

如果我理解你很好,你不需要.getjson和.ajax,因为那些是Ajax调用来检索外部数据吗?

答案 1 :(得分:0)

也许他正试图从文件中获取json?

也许painting.json或绘画是他的json文件。 这将解释他为什么使用ajax和getJson。

你必须明白$ .getJSON使用$ .ajax。

所以:

var painting = [
    {
    "title": "Boardwalk 5",
    "artist": "Arnie Palmer",
    "image": "ap1.jpg",
    "price": 850
    },
    {
    "title": "A Lasting Piece",
    "artist": "Arnie Palmer",
    "image": "ap2.jpg",
    "price": 450
    },
    {
    "title": "Surf at High Tide",
    "artist": "Arnie Palmer",
    "image": "ap3.jpg",
    "price": 950
    },
    {
    "title": "The Games We Play",
    "artist": "Arnie Palmer",
    "image": "ap4.jpg",
    "price": 850
    }
  ];
  $(document).ready(function () {

    $.getJSON('painting.json', function(data){
        $.each(data, function(k,v){
            var title = v.title;
            var price = v.price;
            $('#container').append('<div class="painting"><br/><div class="title">' + title  + '<br/>$' + price + '</div></div>')
        });

     });
});

就够了