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结尾,下下去,可以把这个去掉就可以了。

你可能感兴趣的:(JavaScript,html,jquery,json,PHP)