How PHP and JS communicate data to each other through JSON discussion on _php skills

Source: Internet
Author: User
Tags eval php and string format urlencode
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 directly read JSON data, but PHP provides the Json_decode function to transform JSON data so that it can be accessed by PHP scripts. At the same time, PHP also provides a json_encode function to convert data into JSON format. So, the native JSON in JS and PHP through the Json_encode function after the conversion of JSON is exactly the same? Today, the webmaster and everyone together to discuss this issue.

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

1, one-dimensional array
Consider PHP arrays
Copy Code code as follows:

$array =array ("1", "2", "3");

After converting using the Json_encode function, the corresponding JSON string is
Copy Code code as follows:

["1", "2", "3"].

Careful friend soon found that the conversion of the resulting JSON string, is the form of JavaScript in the array, then can be accessed using JS array access?
Of course it's OK, but when you pass this JSON string to JS, you need to encode it using the UrlEncode function, such as:
Copy Code code as follows:

<a href= "Javascript:show (' <?php echo urlencode (" Array (' 1 ', ' 2 ', ' 3 '));? > ') "id=" AJ "> Visit json</a>

We can use the following JS code to verify:
Copy Code code as follows:

function Show (str) {
var jobj=eval_r (decodeURI (str));
Alert (jobj[2]);
}

If you try it yourself, you'll 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 over, and you get the value of the third character in the string without converting it.
Let's make a change to this one-dimensional array, and we find that the one-dimensional array above does not specify an index, so it defaults to the numeric index, and now we're going to add the key name to it:
Consider PHP arrays
Copy Code code as follows:

$array =array (' A ' => ' 1 ', ' B ' => ' 2 ', ' C ' => ' 3 ');

After converting using the Json_encode function, the corresponding JSON string is
Copy Code code as follows:

{"A": "1", "B": "2", "C": "3"}


We soon found the difference, the most obvious is the string at both ends of the [] into the {}, then this string can also be processed as the above by JS access it? Let's not try:
Copy Code code as follows:

<a href= "Javascript:show" (' <?php echo urlencode (Json_encode (Array (' A ' => ' 1 ', ' B ' => ' 2 ', ' C ' => ' 3 '));? > ') "id=" AJ "> Visit json</a>
function Show (str) {
var jobj=eval_r (decodeURI (str));
alert (JOBJ.A);
}

If you try to know, click on the link, there is no bounce window. Why, then? is the JSON string format of PHP generated wrong? No, this is when we use the Eval function to explain the error. Replace the above function code with the following:
Copy Code code as follows:

function Show (str) {
var jobj=eval_r (' +decodeuri (str) + ');
alert (JOBJ.A);
}

Try it again! How about, you can visit the bar. This tells us that when you use 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, Stationmaster also did not know, standing on the shoulder of the giant.
Note here that although the JSON string generated by PHP
{"A": "1", "B": "2", "C": "3"} was passed to JS can not be directly interpreted as JSON format, but if you use this string in JS directly create JSON data, it is OK. Try the following code:
Copy 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 transformation of two-dimensional arrays. With the example above to pave, the following webmaster directly to show example code:
Copy Code code as follows:

<a href= "Javascript:show" (' <?php echo urlencode (Json_encode (Array (' 1 ', ' 2 ', ' 3 ')));? > ') "id=" AJ "> Visit json</a>
function Show (str) {
var jobj=eval_r (decodeURI (str));
Alert (jobj[0][0]);
}

As you run, you'll find that this is similar to a one-dimensional array, which is an example without a key name, so in the show function, it's OK to remove the parentheses at the ends of the string.
Now, let's take a look at the two-dimensional array and add the key name to the second dimension, and see the sample code:
Copy Code code as follows:

<a href= "Javascript:show (' <?php echo urlencode (Json_encode (Array (" A "=> ' 1 '," B "=> ' 2 ', ' 3 ')); > ') "id=" AJ "> Visit json</a>
function Show (str) {
var jobj=eval_r (' +decodeuri (str) + ');
alert (JOBJ[0].A);
}

After we ran the code, we found that we had a bit of a different way of accessing the JSON data here. The top we're using is
Alert (jobj[0][0]);
And here we are using the
alert (jobj[0].a); Don't ask me why, that's it. That's how JSON is accessed.
In the example above, we add the key name to the second dimension of the two-dimensional array, and we add the key name to the first dimension to see what the difference is in the access mode:
Copy Code code as follows:

<a href= "Javascript:show (' <?php echo urlencode (Json_encode (Array (' K ' =>array (' 1 ', ' 2 ', ' 3 '))");? > ') "id=" AJ "> Visit json</a>
function Show (str) {
var jobj=eval_r (' +decodeuri (str) + ');
Alert (jobj.k[1]);
}

Here we are using the
JOBJ.K[1] Such a way, you must have found that, as long as the array contains the key name, when the array is converted to JSON format, you need to use the
The JSON object. Key Name
This way to access the elements under the key, in the example above, the array element under the K key is a numeric index, so it is accessed in JSON using K[1.
Next, we add the key names to the first and second dimensions of the array:
Copy Code code as follows:

<a href= "Javascript:show (' <?php echo urlencode (Json_encode (Array (' K ' =>array (" A "=> ' 1 ', ' 2 ', ' 3 ')));? > ') "id=" AJ "> Visit json</a>
function Show (str) {
var jobj=eval_r (' +decodeuri (str) + ');
alert (JOBJ.K.A);
}

As mentioned above, as long as you include the key name, you must
The 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 the way JSON is accessed, and only the inventor of JavaScript can explain to you why he has to do so.
Conclusion:
1, convert the array in PHP into a JSON string passed to JS. If the array does not specify a key name, you can use the Eval method of JS directly into the JSON format for JS processing, if the array contains a key name, then use 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, if it's a digital index, use
JSON object [1]
Or
The JSON object. Key Name [1]
Such a way.
Above, we mainly discuss the things that need to be noted when PHP passes the JSON string to JS. Let's discuss what to do when you pass a JSON string to PHP with JS.
Smart you must already know, as long as the JSON data in quotation marks as a string passed to PHP "usually Ajax" can be decoded with the Json_decode function. That's right! That's it! But be careful when constructing JSON strings, and if you don't often construct JSON strings, 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 build it in JS according to the result you want!
OK, today we'll talk about how to use JSON data to communicate between PHP and JS. Here, you can try it again. How to pass the PHP object type to the JS after JSON encoding.

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.