html from表单异步处理

from表单异步处理. 简单处理方法: jQuery做异步提交表单处理, 通过$("#form").serialize()将表单元素的数据转化为字符串, 最后通过$.ajax()执行异步请求资源.

demo示例:

html 文件

 1 <html>
 2 <head>
 3     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
 4     <title>信息登记表异步提交</title>
 5     <style type="text/css">
 6     .grayBox{
 7          backGround-color:#e0e0e0;
 8     }
 9     table{
10         text-align:center;
11     }
12     </style>
13 </head>
14 
15 <body>
16     <form  onsubmit="return false" id="formAsync">
17         <table border="1" rules="all" bordercolor="#000000" >
18             <tr>
19                 <th colspan="2" height="50">信息登记表</th>
20             </tr>
21             <tr class="grayBox" height="70">
22                 <td width="50" >姓名</td>
23                 <td><input type="text" name="username" size="16"/></td>
24             </tr>
25             <tr height="70">
26                 <td>性别</td>
27                 <td>
28                     <input type="radio" name="sex" value="boy" checked="checked"/>29                     <input type="radio" name="sex" value="girl"/>30                 </td>
31             </tr>
32                 <td colspan="2" height="40">
33                     <input type="submit" value="提交信息" onclick="requestAsync()"/>
34                     <input type="reset" value="重置"/>
35                 </td>
36             </tr>
37         </table> 
38     </form>
39 </body>
40 
41 <script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
42 <script type="text/javascript">
43     function requestAsync() {
44         $.ajax({
45             type: "POST",
46             dataType: "json",
47             url: "test.php",
48             data: $('#formAsync').serialize(),
49             success: function (data) {
50                 console.log(data);
51                 if(data.code ==200){
52                     var username = data.msg +' 姓名:'+data.username
53                       alert(username);
54                 }else{
55                       alert(data.msg);
56                 }
57             },
58             error : function() {
59                 alert("操作异常!");
60             }
61         });
62     }
63 </script>
64 </html>

test.php 文件

 1 <?php           
 2 $username = !empty($_POST['username']) ? trim($_POST['username']) :'';
 3 $sex = $_POST['sex'];
 4 
 5 //简单逻辑判断
 6 if($username){
 7     msg(200,'异步处理成功.',$username,$sex);
 8 }else{
 9     msg(400,'数据处理失败,请输入姓名!');
10 }
11 
12 function msg($code,$msg,$username='',$sex=''){
13     exit(json_encode([
14         'code'=> $code,
15         'msg' => $msg,
16         'username' => $username,
17         'sex' => $sex
18         ]));
19 }

结果打印:

 

posted @ 2018-11-06 11:46  echo曦  阅读(4466)  评论(0编辑  收藏  举报