简体   繁体   中英

php json_encode with variable for javascript

For example I want a JSON like this:

{"start": "2015-01-01", "end": "2015-01-01", "backgroundColor": Theme.colors.red}

how to pas Theme.colors.red as constant/variable instead of string to be process in javascript?

my php script currently look like:

$event = new StdClass;
$event->title = $off->note;
$event->start = date('D M d Y', strtotime($off->y.'-'.$off->m.'-'.$off->d));
$event->end = date('D M d Y', strtotime($off->y.'-'.$off->m.'-'.$off->d));
$event->backgroundColor = 'Theme.colors.red';

JSON is a data exchange format. As such, it doesn't know what Theme.colors.red is.

In order to achieve your goal, in Javascript the JSON.parse function can take a second parameter that works as a transforming function. For example:

var data = JSON.parse(rawJSON, function(key, value) {
    // Warning: eval is evil
    if (key === "backgroundColor") return eval(value);

    return value;
});

I don't know what Theme.colors.red is too, its scope and so on, so it's up to you to implement a transformer callback that fits your needs and avoids dangerous pitfalls.

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