至少response.bookings
可以是對象或數組。 如果你發現你什麼,你只是運行console.log(response.bookings);
並檢查調試器控制檯。
作爲對象它可能看起來像(I加入一些虛構字段):
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);
});
作爲一個陣列它可能看起來像(I加入一些虛構字段):
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);
});
一般
是$。每個只有一個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);
}
setInterval call $ .ajax every 10sec; $ .ajax向'{your_domain}/bookings/get/100'發送請求;如果此url正在響應有效的JSON,則調用'success'函數,其中'response'是JSON對象; '.each'在'response.bookings'中的每個項目上運行一個函數; 'sc.status'是用'booking.seat_id'調用的一些自定義函數。 –
謝謝Philipp,我是Jquery的新手,有一部分我不能真正理解。 '$ .each(response.bookings,function(index,booking){ //通過id找到座位並將其狀態設置爲不可用 sc.status(booking.seat_id,'unavailable');'''' JSON對象看起來像?我會很感激你的迴應 – kikuyu1