简体   繁体   English

Rails将JSON字符串转换为Javascript Date()

[英]Rails Convert JSON String To Javascript Date()

I'm returning some json from one of my controllers similar to the following: 我要从我的一个控制器返回一些json,类似于以下内容:

render :json => {
:date => "new Date(new Date('Jan 01 2000').getTime() + #{500.seconds.to_i} * 1000)"
}

I'm expecting it to return a new date set to 500 seconds past midnight (or exactly 00:08:20). 我期望它返回一个新的日期,该日期设置为午夜后500秒(或恰好是00:08:20)。 This json gets passed and processed by a JavaScript function that's expecting a date, however it seems to be interpreting it as a string.. I get an error message similar to: 此json由期待日期的JavaScript函数传递和处理,但是似乎将其解释为字符串。.我收到类似于以下错误消息:

Type mismatch. 类型不匹配。 Value new Date(new Date('Jan 01 2000').getTime() + 500 * 1000) does not match type date 值new Date(new Date('Jan 01 2000')。getTime()+ 500 * 1000)与类型日期不匹配

Running that in the Firebug console produces a perfectly valid date, however. 但是,在Firebug控制台中运行该日期会产生一个完全有效的日期。 How can I get JavaScript to inerpet my json as a date? 如何获取JavaScript作为日期插入我的json?


Edit 编辑

To provide a little more context I'm sending a series of JSON requests to a JavaScript function that build charts using Google's Visualization API. 为了提供更多背景信息,我向JavaScript函数发送了一系列JSON请求,这些JavaScript函数使用Google的Visualization API构建图表。

JSON is not Javascript , it is just a data serialization format, much like XML. JSON不是Javascript ,它只是一种数据序列化格式,非常类似于XML。

What you have is actually a string of Javascript code that you need to interpret (or avoid having to interpret, preferably). 实际上,您所拥有的是一串您需要解释的Javascript代码(或最好避免解释)。 The only way for that to be valid JSON is, indeed, for it to be a string value. 实际上,使JSON有效的唯一方法是使其成为字符串值。 Even then, it should not parse correctly without being inside an array or an object property. 即使这样,它也不能在没有数组或对象属性的情况下正确解析。

You should refactor whatever's returning that Javascript code to instead return just 'Jan 01 2000' , and then do that processing in Ruby. 您应该重构返回该Javascript代码的所有内容,以仅返回'Jan 01 2000' ,然后在Ruby中进行该处理。 Or however it would be best refactored; 或者,最好将其重构; it's hard to tell without more context. 没有更多的上下文很难说。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM