调用的博客园苏恒锋的文章。先收藏,在学习;
http://www.cnblogs.com/in-loading/archive/2012/05/18/2508123.html
程序中两个文件jsonTest1.php和jsonTest2.php。
jsonTest1.php
1 <html> 2 <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 3 <script type="text/javascript" src="js/jquery-1.8.0.js"></script> 4 <head><title>传输数据</title></head> 5 <body> 6 姓名:<input name="name" id="name" type="text" value=""><br/> 7 性别:<input name="sex" id="sex" type="text" value=""><br/> 8 年龄:<input name="age" id="age" type="text" value=""><br/> 9 <input type="submit" name="submit" id="submit" value="提交"> 10 <div style="font-size: 14px;" id="view"> 11 </div> 12 </body> 13 </html> 14 <script type="text/javascript"> 15 $(function(){ 16 $("#submit").click(function(){ 17 var text = $("input").serialize(); 18 // console.log(text); 19 $.ajax({ 20 'type':'POST', 21 'url':'jsonTest2.php', 22 'dataType':'json', 23 'data':text, 24 success:insertData 25 }); 26 }); 27 }); 28 function insertData(data){ 29 var str = "姓名="+data.name+"<br/>性别="+data.sex+"<br/>年龄="+data.age; 30 $("#view").html(str); 31 } 32 </script>
jsonTest2.php
1 <?php 2 /** 3 * Created by PhpStorm. 4 * User: usa007lhy 5 * Date: 15-9-9 6 * Time: 下午7:28 7 */ 8 $json_arg = array( 9 'name'=> $_POST['name'], 10 'sex'=> $_POST['sex'], 11 'age'=> $_POST['age'], 12 ); 13 //$json = new JSON; 14 $json_result = json_encode($json_arg); 15 echo $json_result; 16 ?>