search
HomeBackend DevelopmentPHP TutorialDiscussion 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
javascripjsonphptransferandexisthowusDiscussdataRelatedcombinepassquestion

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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor