jQuery ajax cannot get complex json?
巴扎黑
巴扎黑 2017-05-19 10:34:09
0
5
840

The JSON file code is as follows:

[
{
"name":"炭火烤肉",
"imgsrc":"img/classification.jpg",
"average":167,
"address":"综合楼3楼",
"classify":"bbq",
"recommendation":[
{"food":"和牛拼盘","price":198},
{"food":"精选套餐","price":320},
{"food":"特选牛舌","price":58}
]
}
]

The script code is as follows:

$.ajax({
   url: "json/food.json",
   type: "post",
   dataType: "json", 
   success: function(data) {
       $.each(data.recommendation, function(i, item) {
            var str = '<p>店名:' + item.food + '人均:' + item.price + '</p>';
            document.write(str);
       })
   },
   error : function(XMLHttpRequest, textStatus, errorThrown) {
    alert(XMLHttpRequest.responseText); 
           alert(XMLHttpRequest.status);
           alert(XMLHttpRequest.readyState);
           alert(textStatus); // parser error;
} 
});

The current problem is:
The data.recommendation in the $.each() function seems not to be used in this way (?). The alert displays "Internal Server Error" and the error code is 500,4.
Try to change it to data and change the following item.food and item.price to item.name. Item.average can obtain json normally (the json path is correct). So if I want to get the food and price in the recommendation, how should I change the code?

巴扎黑
巴扎黑

reply all(5)
漂亮男人
$.getJSON("json/food.json", function(data) {
       $.each(data.recommendation, function(i, item) {
            var str = '<p>店名:' + item.food + '人均:' + item.price + '</p>';
            document.write(str);
       });
  });

(Actually, I think it should be fine if I delete the post line. Writing it this way actually saves words)

为情所困

The json file you have above contains an array, so you need to access data[0].recommendation to access the data; you can use console.log(data) which is an [object], so you will know how to solve it.

 $.each(data[0].recommendation, function(i, item) {
            var str = '<p>店名:' + item.food + '人均:' + item.price + '</p>';
            document.write(str);
       })
淡淡烟草味

This json is not complicated. If it is 500, you may first determine whether it is a server problem

给我你的怀抱

500 is an error on the server side

阿神

After the AJAX callback is successful, use console.log(data) to see if the data sent by the server is consistent with the data you want.
In fact, the 500 error is a server error and has nothing to do with how $.each() is used. Others are innocent

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template