Home Backend Development PHP Tutorial Discussion on how php and js transfer data to each other through json_PHP Tutorial

Discussion on how php and js transfer data to each other through json_PHP Tutorial

Jul 21, 2016 pm 03:13 PM
javascrip json php transfer and exist how us Discuss data Related combine pass question

When we combine php and javascript to implement certain functions, json is often used. json is a data format of js and can be parsed directly by js. PHP cannot read json data directly, but PHP provides the json_decode function to convert json data so that it can be accessed by PHP scripts. At the same time, PHP also provides the json_encode function to convert data into json format. So, are the native json in js exactly the same as the json converted by the json_encode function in php? Today, the webmaster will discuss this issue with everyone.

When we pass array data to javascript through php, we usually need to convert it into json format and obtain it through javascript. Let's take the array as an example and first look at the difference between the two.

1. One-dimensional array
Consider PHP array

Copy the code The code is as follows:

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

After conversion using the json_encode function, the corresponding json string is
Copy the code and the code is as follows:

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

Careful friends soon discovered that the json string obtained after conversion is in the form of an array in javascript. So, can it be accessed using the array access method of js?
Of course it is possible, but when you pass this json string to js, ​​you need to use the urlencode function to encode it, such as:
Copy code The code is as follows:

We can use the following js code to verify:
Copy the code The code is 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 in the same way as accessing a one-dimensional array in js. The eval method interprets the json string as a json object, because what is passed is a string. If it is not converted, you will get the value of the third character in the string.
Let’s make some changes to this one-dimensional array. We found that the one-dimensional array above does not have an index specified, so it defaults to a numeric index. Now let’s add a key name to it:
Consider a php array
Copy code The code is as follows:

$array=array('a'=>'1','b'=> ;'2','c'=>'3');

After conversion using the json_encode function, the corresponding json string is
Copy Code The code is as follows:

{"a":"1","b":"2","c":"3"}

.
We soon discovered the difference. The most obvious one is that the [] at both ends of the string became {}. So can this string be processed as above and accessed by js? Let’s give it a try:
Copy the code The code is as follows:

Access json
function show(str){
var jobj=eval_r(decodeURI(str));
alert(jobj.a);
}

If you try it, you will know that after clicking the link, no pop-up window appears. Why? Is the json string format generated by PHP wrong? No, this is when we used the eval function to explain, an error occurred. Replace the above function code with:
Copy code The code is as follows:

function show(str){
var jobj=eval_r('('+decodeURI(str)+')');
alert(jobj.a);
}

Try again! How about it? You can visit now. This tells us that when using the eval method to process a json string with key names, you need to accelerate the brackets at both ends of the string. As for why, the webmaster doesn’t know. He is just standing on the shoulders of giants.
It should be noted here that although the json string
{"a":"1","b":"2","c":"3"} generated by PHP cannot be directly passed to js Interpreted as json format, but if you use this string in js to directly create json data, it is ok. Try the following code:
Copy the code The code is as follows:

var jobj={"a":"1","b":"2","c":"3"};
alert(jobj.b);

2. Two-dimensional array
Two-dimensional array is widely used in PHP, so it is very important to understand the json format after the two-dimensional array is converted. With the above example as a basis, the webmaster will directly give the sample code below:
Copy the code The code is as follows:

Access json
function show(str){
var jobj=eval_r(decodeURI(str));
alert(jobj[0][0]);
}

When you run it, you will find that this is similar to a one-dimensional array. This is an example without key names, so in the show function, it is also possible to remove the brackets at both ends of the string.
Next, we make some changes to the two-dimensional array and add key names to the second dimension. Please see the sample code:
Copy the code The code is as follows :

'1',"b"=> '2','3'))));?>')" id="aj">Access json
function show(str){
var jobj=eval_r('( '+decodeURI(str)+')');
alert(jobj[0].a);
}

After everyone ran the code, we found that here we access json data The way is a little different. Above we used
alert(jobj[0][0]);
and here we used
alert(jobj[0].a); Don’t ask me why, that’s it. This is how json is accessed.
In the above example, we added a key name to the second dimension of the two-dimensional array. Next, we add a key name to the first dimension to see what the access methods are different:
Copy code The code is as follows:

Access json
function show(str){
var jobj=eval_r('('+decodeURI(str)+')');
alert(jobj.k[1]);
}

Here we use
jobj.k[1] This way, you must have discovered that as long as the array contains key names, when the array is converted into json format, you must use
json object. Key name
like this method to access the elements under the key. In the above example, the array element under the k key is a numeric index, so use k[1] to access it in json.
Next, we add key names to both the first and second dimensions of the array:
Copy the code The code is as follows:

'1','2','3') )));?>')" id="aj">Access json
function show(str){
var jobj=eval_r('('+decodeURI(str)+' )');
alert(jobj.k.a);
}

As mentioned above, as long as it contains a key name, it must be accessed in the form of
json object.key name
. If there are multiple keys, use
json object.key name. .Key name...
, don’t ask me why, this is how json is accessed. Only the inventor of javascript can explain to you why he stipulated this.
Conclusion:
1. When converting the array in php into a json string and passing it to js. If the array does not specify a key name, you can directly use the eval method of js to convert it into json format for js processing; if the array contains a key name, you need to use
()
when using the eval method to process it. Surround the json string.
2. If the array contains a key name, after converting it into a json string, use the
json object.key name.key name...
method to access it in js. If it is a numerical index Then use
json object [1]
or
json object.key name [1]
.
Above, we mainly discussed the things that need to be paid attention to when passing json string to js in PHP. Next we will discuss how to process the json string when passing it to php using js.
If you are smart, you must already know that as long as the json data is enclosed in quotes and passed to PHP as a string [usually done with ajax], it can be decoded using the json_decode function. That’s right! That's it! But you must be careful when constructing json strings. If you don’t often construct json strings, you might as well use
echo json_encode(array('k'=>array("a"=>'1', '2','3')))
In this way, view the json format of the target string you need to construct. In this way you can construct it in js according to the results you want!
Okay, today we have discussed how to use json data to communicate between php and js. You can try to pass the object type of php to js after json encoding.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326577.htmlTechArticleWhen we combine php and javascript to implement certain functions, json is often used. json is a data format of js and can be parsed directly by js. PHP cannot read json data directly, but...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Logging CakePHP Logging Sep 10, 2024 pm 05:26 PM

Logging in CakePHP is a very easy task. You just have to use one function. You can log errors, exceptions, user activities, action taken by users, for any background process like cronjob. Logging data in CakePHP is easy. The log() function is provide

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

See all articles