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 JSON instead.

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 $.toJSON and send it with $.post to 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!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章