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?
(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.
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