我想通过ajax加载一些数据,并自动解析日期。
var url = "http://example.com/report_containing_dates.json"
jQuery.getJSON(url, function(data_containing_dates_and_strings){
console.log(date);
});我的json中的日期格式是"2012-09-28“( rails to_json中的默认格式),但jQuery只是将其视为字符串。要让jquery将其解析为日期,日期需要采用什么格式?
回复示例:
{
"columns": [
["date", "Date"],
["number", "active_users"],
],
"rows": [
["2012-09-28", 120, 98, 60],
["2012-09-29", 127, 107, 63]
]
}发布于 2012-10-12 22:57:28
好吧,这比预期的要难得多,但我确实有一个解决方案。
我采用的方法是在ajax请求中请求一个自定义数据类型,然后实现一个自定义转换器。
首先,我在json中使用的日期格式现在是date("yyyy-mm-dd"),原始示例如下:
{
"columns": [
["date", "Date"],
["number", "active_users"],
],
"rows": [
["date(2012-09-28)", 120, 98, 60],
["date(2012-09-29)", 127, 107, 63]
]
}然后,我注册了一个转换器,将文本转换为名为json_with_dates的自定义数据类型。正则表达式用于搜索日期格式,并将其替换为创建日期对象的语句。然后使用Eval来构造json。
jQuery.ajaxSetup({
converters: {
"text json_with_dates": function( text ) {
var with_dates = text.replace(/\"date\(([^)]*)\)\"/g, function(a, date){
var dateParts = date.split("-");
return "new Date(" + dateParts[0] + "," + dateParts[1] + "," + dateParts[2] + ")";
});
var converted = eval("(" + with_dates + ")");
return converted;
}
}
});然后,我对自定义数据类型发出ajax请求:
$.ajax({
url: div.data('chart'),
dataType: 'json_with_dates',
success: function(data_including_dates){
console.log("win!");
}
});发布于 2012-10-12 21:23:14
如何格式化日期字符串并不重要。JSON方法永远不会自动将其转换为Date对象。JSON仅支持以下基本类型:Number、String、Boolean、Array、Object和null。(http://en.wikipedia.org/wiki/JSON)
您必须自己将这些日期字符串转换为Date对象。
在您的情况下,可能是这样的:
$.each(response.rows, function (idx, row) {
row[0] = Date.parse(row[0]);
}发布于 2012-10-12 21:10:29
使用Date.parse,它会将字符串转换为日期。
https://stackoverflow.com/questions/12859777
复制相似问题