AJAX获取JSON形式的数据

test.html:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Document</title>
 6     <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
 7     <script>
 8         $(function(){
 9             var url = 'test.php';
10             $(document).on('click','button',function(){
11                 var params = $('input').serialize();
12                 //alert(params);        //user=test&pwd=123&sex=%E7%94%B7
13                 $.ajax({
14                     url : url,
15                     type : 'get',
16                     data : params,
17                     dataType : 'json',
18                     success : function(msg){
19                         alert(msg.user+"\n"+msg.pwd+"\n"+msg.sex);
20                     }
21                 });
22 
23             });    
24         });
25     </script>
26 </head>
27 <body>
28     用户名:<input type="text" name="user"><br>
29     密 码:<input type="password" name="pwd"><br>
30     性 别:<input type="radio" name="sex" value="男">31             <input type="radio" name="sex" value="女">32     <br>
33     <button>提交</button>
34 </body>
35 </html>

 

 test.php:

1 <?php 
2     echo json_encode($_GET); //对$_GET数组进行 JSON 编码 结果:{"user":"admin","pwd":"123","sex":"\u5973"}
3 ?>

 

 结果:

注意:input中的name属性是必须的!

 

posted @ 2015-11-19 16:30  安静的披风  阅读(242)  评论(0)    收藏  举报