wojkxlq 发表于 2017-4-4 13:21:06

jQuery JSON with PHP json_encode and json_decode

  <!----><!---->




 


http://code.google.com/p/jquery-json/

  Today I looked for a replacement for my old
jspanserializer.js script that I can’t even remember where I found
anymore. Turns out that I wont have to either, I can forget it. From
now on I’ll use jQuery JSONinstead.
  This stuff can really not get any simpler than this:

<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>
 
</head>
 
<body
>
 
<div
 id
="result"
>
</div>
 
</body>
 
</html>


  We initialize some test data, encode it with $.toJSONand send it with $.postto phpfile.php
:

$
res
 = json_decode($_REQUEST
['data'
], true
); 
$
res
["php_message"
] = "I am PHP"

echo
 json_encode($
res
);

  Note the last argument to json_decode
,
omitting it will result in a return type of stdObject which is not what
we want in this simple test. Note that json_decode requires PHP 5.2. If
that is not available you might want to check out an alternative   method.

  And the final output in the result div:

Hello "World" it worked . Message from PHP: I am PHP

  Great!
页: [1]
查看完整版本: jQuery JSON with PHP json_encode and json_decode