php+ajax+json 详解及实例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
< html >
< head >
< meta http-equiv = "content-type" content = "text/html;charset=utf-8" />
< script type = "text/javascript" src = "jquery-1.8.2.min.js" ></ script >
< script type = "text/javascript" >
  $(function(){
    $("#send").click(function(){
     var cont = $("input").serialize();
     $.ajax({
       url:'ab.php',
       type:'post',
       dataType:'json',
       data:cont,
       success:function(data){
        var str = data.username + data.age + data.job;
        $("#result").html(str);
     }
   });
  });
  });
</ script >
</ head >
< body >
< div id = "result" >一会看显示结果</ div >
< form id = "my" action = "" method = "post" >
       < p >< span >姓名:</ span > < input type = "text" name = "username" /></ p >
      < p >< span >年龄:</ span >< input type = "text" name = "age" /></ p >
      < p >< span >工作:</ span >< input type = "text" name = "job" /></ p >
</ form >
< button id = "send" >提交</ button >
</ body >
</ html >

 php页面:

?
1
2
3
4
5
6
7
8
9
10
<?php
header( "Content-type:text/html;charset=utf-8" );
     $username = $_POST [ 'username' ];
     $age = $_POST [ 'age' ];
     $job = $_POST [ 'job' ];
     $json_arr = array ( "username" => $username , "age" => $age , "job" => $job );
     $json_obj = json_encode( $json_arr );
     echo $json_obj ;
?>

使用post方式

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<script type= "text/javascript" >
  $( function (){
  $( "#send" ).click( function (){
    var cont = {username:$( "input" )[0].value,age:$( "input" )[1].value,job:$( "input" )[2].value};
    var url = 'ab.php' ;
    $.post(url,cont, function (data){
     var res = eval( "(" + data + ")" ); //转为Object对象
    var str = res.username + res.age + res.job;
   $( "#result" ).html(str);
   });
  });
  });
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值