This article describes how to use Json to implement data exchange between PHP and JavaScript. For more information, see JSON (JavaScript Object Notation) is a lightweight data exchange format.
In short, both xml and json are used to facilitate data exchange between the client and the server, especially for object-type data, such as the most common array.
The following example transfers the array from php to javascript and the array from javascript to php. The example is simple and you can understand the concept. No matter whether it is sent from php to javascript or javascript to php, json will flat the object, that is, convert one dimension into a string before transmission.
PHP transfers values to JavaScript
Json. PHP file
The code is as follows:
$ Arr = array (
'Name' => 'foot home ',
'Nick '=> 'gonn ',
'Contact '=> array (
'Email '=> 'xxxxxxx @ 163.com ',
'Website' => 'http: // www.jb51.net ',
)
);
$ Json_string = json_encode ($ arr );
Echo "getProfile ($ json_string )";
?>
The result of executing this file is as follows:
The code is as follows:
GetProfile ({"name": "u5e0cu4e9a", "nick": "Gonn ",
"Contact": {"email": "xxxxxxx@163.com", "website": "http://www.jb51.net "}})
Json. php flat the array through the json_encode function, and then sends it. on the contrary, there is a json_decode function.
So how can we call JavaScript? It's easy to define a variable to get Json from PHP. this Json has the object features. we can use array. name to get the Json attributes.
The code is as follows: