我在解释这段代码时遇到了问题,我正在开发一个座位安排Jquery Script。请帮我解释这个jquery代码
setInterval(function() {
$.ajax({
type : 'get',
url : '/bookings/get/100',
dataType : 'json',
success : function(response) {
//iterate through all bookings for our event
$.each(response.bookings, function(index, booking) {
//find seat by id and set its status to unavailable
sc.status(booking.seat_id, 'unavailable');
});
}
});}, 10000); //every 10 seconds
答案 0 :(得分:1)
至少response.bookings
可以是对象或数组。
如果您要找到什么,只需运行console.log(response.bookings);
并检查调试器控制台。
作为一个对象,它可能看起来像(我添加了一些虚构的字段):
var response = {
status: 'ok',
bookings: {
//index: booking
a: {seat_id: 1, user_id: 4, paid: true},
b: {seat_id: 2, user_id: 3, paid: false},
c: {seat_id: 3, user_id: 2, paid: true},
d: {seat_id: 4, user_id: 1, paid: false}
}
};
//$.each means that function is called of each entry of response.bookings
$.each(response.bookings, function(index, booking) {
// frist run index='a', booking={seat_id: 1, user_id: 1, paid: true} so booking.seat_id=1
//second run index='b', booking={seat_id: 2, user_id: 2, paid: false} so booking.seat_id=2
// third run index='c', booking={seat_id: 3, user_id: 3, paid: true} so booking.seat_id=3
// fours run index='d', booking={seat_id: 4, user_id: 4, paid: false} so booking.seat_id=4
sc.status(booking.seat_id, 'unavailable');
// you can check the values by using console again:
// console.log(index);
// console.log(booking);
});
作为一个数组,它看起来像(我添加了一些虚构的字段):
var response = {
status: 'ok',
bookings: [
// array of booking object (index incrementel starting from 0)
{seat_id: 1, user_id: 4, paid: true},
{seat_id: 2, user_id: 3, paid: false},
{seat_id: 3, user_id: 2, paid: true},
{seat_id: 4, user_id: 1, paid: false}
]
};
//$.each means that function is called of each entry of response.bookings
$.each(response.bookings, function(index, booking) {
// frist run index=0, booking={seat_id: 1, user_id: 1, paid: true} so booking.seat_id=1
//second run index=1, booking={seat_id: 2, user_id: 2, paid: false} so booking.seat_id=2
// third run index=2, booking={seat_id: 3, user_id: 3, paid: true} so booking.seat_id=3
// fours run index=3, booking={seat_id: 4, user_id: 4, paid: false} so booking.seat_id=4
sc.status(booking.seat_id, 'unavailable');
// you can check the values by using console again:
// console.log(index);
// console.log(booking);
});
一般是$ .each只有一个for循环的jquery版本。 在这里你如何使用普通的javascript(也许可以帮助你解决):
// response.bookings is an object
var booking;
for (index in response.bookings){
booking = response.bookings[index];
sc.status(booking.seat_id, 'unavailable');
//console.log(booking);
}
// response.bookings is an array
var booking;
for (var index = 0; index < response.bookings,length; index++){
booking = response.bookings[index];
sc.status(booking.seat_id, 'unavailable');
//console.log(booking);
}