JSON of jquery and json_encode of PHP and json_decode (zt translation)

Source: Internet
Author: User

 

PHP code:

<
html


>
<
head

>
<
title
>
Json Test
</
title

>
<
SCRIPT src
=
"jquery
.js"
>
</SCRIPT>

<SCRIPT src="jquery.json.js"></SCRIPT>
<script>
$(document).ready(function(){
   var data = new Object();
   data.hello = "Hello";
   data.world = 'World';
   data.worked = " it worked ";
   data.somebool = true;
   data.array = new Array("he/"ll/"o", '"World"');
   var dataString = $.toJSON(data);
   $.post('phpfile.php', {data: dataString}, function(res){
     var obj = $.evalJSON(res);
     if(obj.somebool === true)
       $("#result").html(obj.hello + ' ' + obj.array[1] + obj.worked + ". Message from PHP: "+obj.php_message);
   });
});
</script>

<body>
<div id="result"></div>
</body>



We initialize some test data, use the $. tojson method to encode it, and use the $. Post method to send it to phpfile. php:

Copy the PHP content to the clipboard.

PHP code:

$res =
json_decode
(
$_REQUEST
[
'data'
],
true

);

$res
[
"php_message"
] =
"I am PHP"

;
echo
json_encode
(
$res
);


Note that the last parameter of json_decode will return a stdobject object, but this is not the data type we want in this simple test.

The output result is as follows:
Hello "world" It worked. Message from PHP: I am PHP

Very good!

 

 

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.