jquery与php的json交互

This plugin exposes four new functions onto the $, or jQuery object:

* toJSON: Serializes a javascript object, number, string, or arry into JSON.
* evalJSON: Converts from JSON to Javascript, quickly, and is trivial.
* secureEvalJSON: Converts from JSON to Javascript, but does so while checking to see if the source is actually JSON, and not with other Javascript statements thrown in.
* quoteString: Places quotes around a string, and inteligently escapes any quote, backslash, or control characters.

<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>
我们初始化一些数据, 使用$.toJSON进行编码并使用$.post发送到phpfile.php :
$res = json_decode($_REQUEST['data'], true);
$res["php_message"] = "I am PHP";
echo json_encode($res);
最后将参数转为json编码,
值得注意的是最后的争论json_decode、省略它会导致返回类型的stdObject并不是我们想要在这个简单的测试。注意json_decode需要PHP 520。如果这不是可得到的,你可能想要查看了另一种方法。
而最终产品的结果处理:
  Hello "World" it worked . Message from PHP: I am PHP
太棒了!

附件里面是jquery.json.js后面由于上传问题,加了.rar结尾,下下去,可以把这个去掉就可以了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值