简体   繁体   中英

send array of Javascript constructors from PHP to Javascript

I am trying to send an array back to Javascript from PHP. I'm using Ajax to do this. I know how to send arrays to Javascript, but this time I'm trying to send an array that contains some Javascript constructors. 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? 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?

Can not you just simply send value of new Date() instead of constructor? 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. 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. 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. You can serialize the Date with some PHP func like date , send it via Ajax, and then deserialize it on 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
const response = ...
const myData = new Data(response[0]); // Will be Date obj.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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