Jquery $ .ajax,dataType解析错误

时间:2017-03-09 18:15:02

标签: javascript jquery ajax

我已经解决了与我的问题相关的其他问题,但解决方案dint对我有用。这是我的ajax代码:

   $.ajax({
     url:'http://localhost:8080/items?callback=?',
     type:'GET',
     //the name of the callback function
     jsonp: "jsonpcallback",
     dataType:'jsonp',

     success:function(data){
        alert("hello" + data);
         var length = data.length;
         for(var i=0;i<length;i++){
           var object = data[i];
           var item = new Item(object.id,object.name,object.price,object.quantity);
           $("#items-container").append(getItemHtml(item.id));

         }

     },
     error:function(xhr,status,error){
        alert(status);
     }
 });

这是我的回调函数:

function jsonpcallback(data){
 console.log(data);
}

我收到一个名为parse错误的错误。有人可以告诉我哪里出错了???来自服务器的响应没有任何错误。

修改 添加了服务器响应:

 [
  {
    "id": 1,
    "name": "Snickers",
    "price": 1.5,
    "quantity": 7
  },
  {
    "id": 2,
    "name": "M&M's",
    "price": 1.25,
    "quantity": 8
  },
  {
    "id": 3,
    "name": "Almond Joy",
    "price": 1.25,
    "quantity": 11
  },
  {
    "id": 4,
    "name": "Milky Way",
    "price": 1.65,
    "quantity": 3
  },
  {
    "id": 5,
    "name": "Payday",
    "price": 1.75,
    "quantity": 2
  },
  {
    "id": 6,
    "name": "Reese's",
    "price": 1.5,
    "quantity": 5
  },
  {
    "id": 7,
    "name": "Pringles",
    "price": 2.35,
    "quantity": 4
  },
  {
    "id": 8,
    "name": "Cheezits",
    "price": 2,
    "quantity": 6
  },
  {
    "id": 9,
    "name": "Doritos",
    "price": 1.95,
    "quantity": 7
  }
]

1 个答案:

答案 0 :(得分:1)

您的通话响应是JSON,而不是JSONP。它们不可互换。要将此集dataType修复为'json',请删除对JSONP回调的引用。试试这个:

$.ajax({
  url: 'http://localhost:8080/items',
  type: 'GET',
  dataType: 'json',
  success: function(data) {
    console.log(data); // only for testing

    var length = data.length;
    for (var i = 0; i < length; i++) {
      var object = data[i];
      var item = new Item(object.id, object.name, object.price, object.quantity);
      $("#items-container").append(getItemHtml(item.id));
    }
  },
  error:function(xhr, status, error) {
    alert(status);
  }
});