【问题标题】:jquery ajax how should it format dates?jquery ajax 应该如何格式化日期?
【发布时间】:2016-05-11 08:48:50
【问题描述】:

我使用 jquery 与 REST API 进行通信。 (ASP.net Web API)。

我创建了一个简单的对象,然后使用 jquery 将它“PUT”到服务器上:

var myObject = {
  name: 'just a name',
  createDate: new Date()
}
$.ajax({
  url: 'https://myServer/api/person/1',
  dataType: 'json',
  method: 'put',
  data: myObject
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

查看 Firebug 中的网络流量,我可以看到我的 createDate 属性通过以下方式发送:

Tue Feb 02 2016 14:40:26 GMT+0100 (W. Europe Standard Time)

这将是 new Date().toString() 的默认渲染

我的 API 并不明显不喜欢这样,它接受多种格式的日期,并且确实很好地处理了普通的 JSON 版本:

new Date().toJSON()
results to: "2016-02-02T13:45:37.069Z"

如何处理?我不希望通过“手动”将每个日期转换为 JSON 来发布我的对象,这样可以轻松处理复杂的对象。

我能做什么(警告即将出现非常肮脏的伎俩),覆盖日期对象的默认 toString 方法:

Date.prototype.toString = new Date().toJSON

这行得通……但是……太糟糕了!

有什么想法吗?

【问题讨论】:

  • 从你的问题的散文看来,你在谈论你发送客户端服务器的东西,但是你的@987654327 @call 根本没有向服务器发送 JSON,它发送的是通常的 URI 编码格式。 dataType 告诉 jQuery 你期望从服务器 返回 什么,而不是你 发送 它。

标签: jquery json ajax date


【解决方案1】:

所以,感谢 T.J. 的回答和一些进一步的探索,这就是我想出的,有人可能会觉得它有用。

目标:发布一个包含日期的对象,将它们作为 JSON 通过线路发送。锦上添花:使用本地化日期对象而不是 UTC 日期,因为我碰巧喜欢这样 ;)

/* 
	add a toJSONlocal method to the date object
	takes the date, corrects the time zone and gives json output without the 'Z' at the end 
*/
Date.prototype.toJSONlocal = function() {
	var local = new Date(this); 
	local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
	return local.toJSON().substring(0,23)
}

/* 
	replacer function to use with JSON.stringify() 
	checks if the received string is an ISO Date, if so make it local.
*/
jsonDateLocalizer = function(key, value) {
	if(typeof value == 'string' && value.match(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/)) {
		return(new Date(value).toJSONlocal())
	}
	return value;
};



var myObject = {
  name: 'Bobby Tables',
  createDate: new Date()
}
$.ajax({
	url: 'https://myServer/api/person/1', // send it here
	dataType: 'json', // expect json in return
	method: 'put', // let's do a PUT request
	contentType:"application/json; charset=utf-8", //tell the server I'm sending json.
	data: JSON.stringify(myObject, jsonDateLocalizer) // here you go, json data, with dates the way I like 'em
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    【解决方案2】:

    JSON.stringify 接受一个“替换器”参数,该参数可以是几件事,包括一个可用于为属性生成适当值的函数。您可以使用它来将日期替换为您的服务器随后会检测并转换回日期的格式。

    例子:

    var data = {
      dt: new Date()
    };
    document.body.innerHTML = JSON.stringify(data, function(key, value) {
      if (value instanceof Date) {
        return value.toISOString();
      }
      return value;
    });

    或者有微软首选的/Date(mssinceepoch)/

    document.body.innerHTML = JSON.stringify(data, function(key, value) {
      if (value instanceof Date) {
        return "/Date(" + value.getTime() + ")/";
      }
      return value;
    });
    

    无论哪种方式,您的服务器都必须检测这些(通过键的名称,或通过值的模式等)并将它们转换回日期。

    您的ajax 电话将更改为:

    var myObject = {
      name: 'just a name',
      createDate: new Date()
    };
    $.ajax({
      url: 'https://myServer/api/person/1',
      contentType: 'json',
      method: 'put',
      data: JSON.stringify(myObject, myReplacerFunction)
    });
    

    唯一的区别是调用JSON.stringify。此外,您在调用中输入了dataType: 'json',但如果您发送 JSON,则使用contentType 告诉服务器它是什么,而不是dataTypedataType 告诉 jQuery 你希望服务器发送什么返回

    【讨论】:

    • 嗨 T.J.谢谢你的信息,我已经在摆弄这些线了。我认为这将在不使用替换器的情况下工作。在日期对象上调用 JSON.stringify() 时,日期首先由 Date.toJSON 处理,这已经转换为 ISO 日期。让我知道我实际上不想要 ISO 日期,只需要 localDates,但我想我可以使用替换器来处理它!
    • 谢谢 T.J.我在下面添加了解决方案。
    猜你喜欢
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 2020-11-05
    • 2011-09-20
    • 2011-06-15
    • 1970-01-01
    • 2013-10-20
    • 2011-10-06
    相关资源
    最近更新 更多