【发布时间】:2016-02-06 20:00:27
【问题描述】:
我需要使用 fullcalendar.io 创建日历视图。要使用日历,我需要像这样创建一个 JSON:
var db_data = [
{
"id": 5,
"user_id": 1,
"article_id": 5,
"title": "",
"start": "2016-03-25 15:18:46"
},
{
"id": 4,
"user_id": 1,
"article_id": 5,
"price": 55,
"title": "",
"start": "2016-03-15 15:18:46"
} etc.
我需要从 period_start 到 period_end 的每个日期在日历上输入价格,但对于某些价格我在数据库中有值,而对于其他我没有,所以我需要使用标准价格(等 50 美元)...
所以我有 period_start 和 period_end,并且我从数据库中获取了一些数据,但现在我需要创建一个 JSON,其中包含不在数据库中的日期对象,因此我创建了代码:
function fulljson (){
var db_data;
$.ajax({
url: "http://localhost:8888/diving/{{$article->id}}",
type: "GET",
async: true,
dataType: "json",
success: function(data) {
db_data = data;
console.log(db_data);
// declare variables
var period_start = new Date('{{ date('Y-m-d', strtotime($article->from)) }}'),
period_end = new Date('{{ date('Y-m-d', strtotime($article->to)) }}'),
current_date = period_start,
array_of_all_dates = [];
// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
array_of_all_dates.push(current_date);
current_date = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
}
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // I need to do this comparison better!
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
title: '',
start: date,
price: '{{$article->price}}'
};
console.log(new_object);
return new_object;
});
console.log('result'+array_of_all_dates);
drawCalendar(array_of_all_dates);
},
error: function (data) {
console.log(data);
console.log('ERROR');
}
});
};
$(document).ready(function() {
fulljson();
});
function drawCalendar(data) {
$('#calendar').fullCalendar({
header: {
left: 'prev today',
center: 'title',
right: 'next'
},
defaultDate: Date.now(),
eventRender: function(event, element) {
element.find("fc-event-container").remove();
element.find(".fc-content").remove();
element.find(".fc-event").remove();
var new_description =
'<div style="display:inline-flex; float:right;"><div class="col-md-6"style="margin-top:5px";><p class="price">' + event.price + 'e</p></div>';
element.append(new_description);
} ,// allow "more" link when too many events
events: data,
loading: function(bool) {
$('#loading').toggle(bool);
}
}
});
};
请看 1.2.3。二月,我有来自数据库的数据。您将看到更改。
那么为什么这段代码在 Chrome 中有效,而在 Firefox 中无效?什么是问题?有没有更好的办法来解决这个问题?
【问题讨论】:
-
我怎样才能更好地解决这个比较:while (current_date.getTime() 0) { return found_in_db[0]; } ...
-
我很难看出这两个屏幕截图之间的区别。什么是 1.2.3?
-
请查看日期 1. 二月, 2. 2 月 3 日 ... 价格 ...
标签: javascript jquery arrays json object