简体   繁体   English

从PHP发送Javascript构造函数数组到Javascript

[英]send array of Javascript constructors from PHP to Javascript

I am trying to send an array back to Javascript from PHP. 我正在尝试将数组从PHP发送回Javascript。 I'm using Ajax to do this. 我正在使用Ajax来做到这一点。 I know how to send arrays to Javascript, but this time I'm trying to send an array that contains some Javascript constructors. 我知道如何将数组发送到Javascript,但是这次我试图发送包含一些Javascript构造函数的数组。 For example I want to be able to send this: [new Date(2017,06,03), 25, 33] Is there a way to send this array to Javascript? 例如,我希望能够发送此消息: [new Date(2017,06,03), 25, 33]有没有办法将此数组发送给Javascript? If so, how will Javascript be able to use this array in a way where a new Date is created in the first index of the array? 如果是这样,那么Javascript如何在数组的第一个索引中创建新Date的方式使用此数组?

Can not you just simply send value of new Date() instead of constructor? 您不能只是简单地发送new Date()值而不是构造函数吗? Will be more effective i assume. 我认为会更有效。

Short answer: No, there is no direct way. 简短的回答:不,没有直接的方法。

Long answer: When you say that you send arrays to Javascript from PHP, you need to understand that PHP is a server side language, and Javascript is what runs in the browser. 长答案:当您说要从PHP向Javascript发送数组时,您需要了解PHP是服务器端语言,而Javascript是浏览器中运行的语言。 So, in between them, u have the network layer and all the things that transfers on that layer should be serializable, usually means strings. 因此,在它们之间,您具有网络层,并且在该层上传输的所有事物都应该可序列化,通常表示字符串。

So the data that you pass to the browser via Ajax usually is JSON. 因此,您通过Ajax传递给浏览器的数据通常是JSON。 It can contain only primitive values, like: string, number, boolean, null. 它只能包含原始值,例如:字符串,数字,布尔值,空值。

new Date(2017,06,03) is an javascript object, that is not part of JSON spec. new Date(2017,06,03)是一个javascript对象,不属于JSON规范。 You can serialize the Date with some PHP func like date , send it via Ajax, and then deserialize it on Javascript world. 您可以使用某些PHP函数(例如date序列化Date,通过Ajax发送,然后在Javascript world中反序列化。

Something like that: 像这样:

<?php
    /* your Ajax return */
    echo json_encode(array(date('c', mktime(0, 0, 0, 7, 1, 2000)), 25, 33)); // will return ["2000-07-01T00:00:00-07:00",25,33]
?>

Then on the JavaScript part u can parse it with Date constructor. 然后在JavaScript部分,您可以使用Date构造函数对其进行解析。

// Javascript
const response = ...
const myData = new Data(response[0]); // Will be Date obj.

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

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