1. 程式人生 > >html from表單異步處理

html from表單異步處理

操作 console alt font 字符串 ons pan cti all

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 }

結果打印:

技術分享圖片

html from表單異步處理