显示通过JSONP调用的JSON数据时出现问题。我已经通过URL跨域传递了一个复杂的JSON文件,而且我是JSON和Ajax的新手。我在https://learn.jquery.com/ajax/working-with-jsonp/上关注了JSONP文章,这很有效。现在,在遵循这个问题How do I iterate through this JSON object in jQuery?之后,我尝试遍历JSON对象并在HTML页面中显示数据,而且我什么也不会去。数据未定义,我不确定自己在做什么错:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
我希望这是对我们那里的更高级用户的明显解决方案:)
最佳答案
那是因为您的data
对象不存在。您要引用的data
键位于要传递给$.ajax
方法的对象上。
您需要在success
回调内部执行函数,以使其有意义。
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});