PHP和javascript:將新日期作為json傳遞

[英]PHP and javascript: pass new Date as json


I utilize google chart table. In DataTable i need a date and for example, the javascript code must be the following:

我利用谷歌圖表。在DataTable中我需要一個日期,例如,javascript代碼必須如下:

rows: [{c:[{v: 'Mike'}, {v: new Date(2008, 1, 28), f:'February 28, 2008'}]},

How can i pass the

我怎么能通過

new Date(2008, 1, 28)

as json object from php?

作為json對象從PHP?

I have done:

我已經做好了:

....
array('v' => "new Date($timeStamp)");
...
$output = json_encode($table);

but in the javascript i receive new Date(2008, 1, 28) as string and doesn't instantiate new date.

但在javascript中我收到新的日期(2008,1,28)作為字符串,並沒有實例化新的日期。

How can i instantiate a new Date()?

我如何實例化一個新的Date()?

Thanks

2 个解决方案

#1


0  

You can do this one in you javascript:

你可以在你的javascript中執行此操作:

var date = eval("new Date(2008, 1, 28)"); // Here should paste the string that you receive.

That should eval it.

那應該評估它。

#2


0  

The JavaScript object you want to get to is not JSON, as JSON does not allow the new keyword, nor the call of a function, like Date().

您想要獲取的JavaScript對象不是JSON,因為JSON不允許使用new關鍵字,也不允許調用函數,如Date()。

What you could do, is move away from pure JSON, like this:

你能做什么,就是擺脫純粹的JSON,就像這樣:

<?
$timeStamp = time (); // UNIX epoch

$table = array(
    array('v' => 31415926535), // some unique number, that does not occur elsewhere
);
$output = json_encode($table);
// Alter JSON, and now you cannot call it JSON anymore:
$output = str_replace($table[0]['v'], "new Date($timeStamp)", $output);
?>
<script>
    var table = {
        ...
        rows: <?= $output ?>,
        ...
    };
    ...
</script>

Make sure the $timeStamp is either a number representing a UNIX epoch (like example abopve), or a string, well-formatted for JavaScript to interpret as a date. In the latter case you will need to wrap $timeStamp in single quotes.

確保$ timeStamp是代表UNIX紀元的數字(例如abopve),或者是一個字符串,格式良好,可以將JavaScript解釋為日期。在后一種情況下,您需要將$ timeStamp包裝在單引號中。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/05/06/720aa481c5e1625b80fedbab6233eae1.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com