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!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值