


Discussion on how php and js transfer data to each other through json_PHP Tutorial
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
$ array=array("1","2","3");
After conversion using the json_encode function, the corresponding json string is
["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:
We can use the following js code to verify:
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
$array=array('a'=>'1','b'=> ;'2','c'=>'3');
After conversion using the json_encode function, the corresponding json string is
{"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:
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:
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:
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:
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:
'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:
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:
'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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.
