How PHP and JS communicate data to each other through JSON

Source: Internet
Author: User
JSON is often used when we implement certain functions in conjunction with PHP and JavaScript. JSON is a data format of JS, can be directly parsed by JS. PHP cannot read JSON data directly, but PHP provides the Json_decode function to convert JSON data, which can be accessed by PHP scripts. PHP also provides the Json_encode function to convert the data into JSON format. So, is the native JSON in JS identical to the JSON that was converted by the Json_encode function in PHP? Today, the stationmaster and everybody together to discuss this question.

When we pass the array data to JavaScript through PHP, we usually convert it to JSON format, and then we use the JavaScript to get it, so let's take an array as an example to see the difference between the two.

1. One-dimensional arrays
Consider the PHP array
Copy the code code as follows:
$array =array ("1", "2", "3");

After conversion using the Json_encode function, the corresponding JSON string is
Copy the code code as follows:
["1", "2", "3"].

The attentive friend quickly discovered that the converted JSON string, which is the array form in JavaScript, could be accessed using the JS array access method.
Of course it is possible, but when you pass this JSON string to JS, you need to encode it using the UrlEncode function, such as:
Copy the code code as follows:
<a href= "http://www.php.cn/" >
We can use the following JS code to verify:
Copy the code code as follows:
function Show (str) {
var jobj=eval_r (decodeURI (str));
Alert (jobj[2]);
}

If you try it yourself, you will find that, yes, you can access it by accessing a one-dimensional array in JS. The Eval method interprets the JSON string as a JSON object because the string is passed, and if you do not convert it, you get the value that will be the third character in the string.
Let's make a change to this one-dimensional array, and we find that the one-dimensional array above does not have an index, so it defaults to a numeric index, and now let's add the key name:
Consider the PHP array
Copy the code code as follows:
$array =array (' a ' = ' 1 ', ' b ' = ' 2 ', ' c ' = ' 3 ');

After conversion using the Json_encode function, the corresponding JSON string is
Copy the code code as follows:
{"A": "1", "B": "2", "C": "3"}


We soon discovered the difference, the most obvious is that the string at both ends of the [] into {}, then this string can also be treated as above after the JS access it? We don't have a chance to try:
Copy the code code as follows:
<a href= "http://www.php.cn/" >function Show (str) {
var jobj=eval_r (decodeURI (str));
alert (JOBJ.A);
}

If you try, you will know that after clicking on the link, there is no pop-up window. Why is it? is PHP generated JSON string format is not correct? No, this is an error when we use the Eval function to explain. Replace the above function code with:
Copy the code code as follows:
function Show (str) {
var jobj=eval_r (' (' +decodeuri (str) + ') ');
alert (JOBJ.A);
}

Try it again! How about, can you visit it. This tells us that when using the Eval method to process a JSON string with a key name, you need to accelerate the parentheses at both ends of the string. As for why, the webmaster did not know, standing on the shoulders of giants.
It is important to note that although the JSON string generated by PHP
{"A": "1", "B": "2", "C": "3"} cannot be interpreted directly as JSON after being passed to JS, but it is OK if you use the string in JS to create JSON data directly. Try the following code:
Copy the code code as follows:
var jobj={"A": "1", "B": "2", "C": "3"};
alert (JOBJ.B);

2, two-dimensional array
Two-dimensional arrays are widely used in PHP, so it is important to understand the JSON format after the conversion of two-dimensional arrays. With the above example to pave the table, the following webmaster directly to show example code:
Copy the code code as follows:
<a href= "http://www.php.cn/" >function Show (str) {
var jobj=eval_r (decodeURI (str));
Alert (jobj[0][0]);
}

When you run, you will find that this is similar to a one-dimensional array, which is an example without a key name, so it is possible to remove the parentheses at both ends of the string in the show function.
Now, let's change the two-dimensional array and join the key name in the second dimension, see the sample code:
Copy the code code as follows:
<a href= "http://www.php.cn/" >function Show (str) {
var jobj=eval_r (' (' +decodeuri (str) + ') ');
alert (JOBJ[0].A);
}

When we ran the code, we found that the way we accessed JSON data was a little different. We used it on the top.
Alert (jobj[0][0]);
And here's what we're using.
alert (jobj[0].a); Don't ask me why, that's it. This is how JSON is accessed.
In the above example, we add a key name to the second dimension of the two-dimensional array, and we add the key name to the first dimension to see how the access is different:
Copy the code code as follows:
<a href= "http://www.php.cn/" >function Show (str) {
var jobj=eval_r (' (' +decodeuri (str) + ') ');
Alert (jobj.k[1]);
}

Here we are using the
JOBJ.K[1] This way, you must have found that, as long as the array contains the key name, when the array is converted to JSON format, it is necessary to use
JSON object. Key Name
This way to access the element under the key, in the example above, the array element under the K key is a numeric index, so it is accessed in a way that uses k[1] in JSON.
Below, we add key names to both the first and second dimensions of the array:
Copy the code code as follows:
<a href= "http://www.php.cn/" >function Show (str) {
var jobj=eval_r (' (' +decodeuri (str) + ') ');
alert (JOBJ.K.A);
}

As mentioned above, as long as the key name is included, it must be
JSON object. Key Name
The way to access, if there are multiple keys to use
JSON object. Key name. Key Name ...
, don't ask me why, this is how JSON is accessed, and only the inventor of JavaScript can explain to you why he does so.
Conclusion:
1, convert the array in PHP into a JSON string when passed to JS. If the array does not specify the key name, then you can directly use the JS eval method to convert it to the JSON format for JS processing, if the array contains a key name, then when using the Eval method to process, you need to use the
()
Enclose the JSON string.
2, if the array contains the key name, converted to a JSON string, in JS to use
JSON object. Key name. Key Name ...
The way to access it, and if it is a numeric index, use the
JSON object [1]
Or
JSON object. Key Name [1]
Such a way.
Above, we mainly discuss the things to be aware of when PHP passes JSON strings to JS. Let's talk about what to do with JS when passing JSON strings to PHP.
Smart you must already know, as long as the JSON data quoted in quotation marks as a string to PHP "usually with Ajax" can be decoded with the Json_decode function. That's right! That's it! But be careful when constructing JSON strings, if you don't construct JSON strings often, you might want to use
echo json_encode (Array (' K ' =>array ("a" = ' 1 ', ' 2 ', ' 3 ')))
In this way, look at the JSON format of the target string you need to construct. So you can be in JS based on the results you want to construct!
Well, today, how to communicate between PHP and JS using JSON data is discussed here, you can try to use the PHP object type JSON encoding after how to pass to JS.
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.