ajax提交form表單

  1. ajax提交form表單和不一樣的form表單的提交主要區別在於,ajax提交表單是異步提交的,而普通的是同步提交的表單。javascript

  

  2. from視圖部分php

 1 <form id="loginForm" name="loginForm" action="admin/user/login" method="post">
 2     <table  align="center">
 3         <tr>
 4             <td>用戶名:</td>
 5             <td colspan="2"><input type="text" name="username" id="username" /></td>
 6          </tr>
 7          <tr>
 8             <td>密  碼:</td>
 9             <td colspan="2"><input type="password" name="password" id="password" /></td>
10          </tr>
11             <td colspan="3" align="center">
12                  <input id="login_submit_button" type="submit" value="登陸"/>
13             </td>
14          </tr>
15      </table>
16 </form>

  3. ajax提交html

 1 //加載js
 2 <script src = "../js/jquery-1.4.min.js" type = "text/javascript"></script>
 3 <script type = "text/javascript">
 4 $('#loginForm').on('submit', function (e){
 5        e . preventDefault();
 6        $.ajax( {
 7        type : "POST",
 8        dataType: "json",
 9        url : 'url',
10        data : $(this) . serialize(),
11        success : function (res) {
12         console . log(res)
13              if (res . type == 'ok') {
14                  alert(res . msg);
15                  //成功後跳轉路由設置
16                  window . location . href = '';
17               } else {
18                  if (res . type == "no") {
19                       alert(res . msg);
20                       }
21                   }
22               }
23            });
24          });
25 </script>

 

  4. 後臺處理(php) java

  

 1 //首先判是否有ajax提交  
 2 if (!Yii::app()->request->isAjaxRequest)
 3 {
 4 Yii::app()->end();
 5 }
 6 
 7 $model = new XXX;
 8 
 9 if (isset($_POST['FrontLogin'])) {
10     //像通常的form提交取值
11     $model->username = $_POST['FrontLogin']['username'];
12     $model->password = md5($_POST['FrontLogin']['password']);
13     $model->verifyCode = $_POST['LoginForm']['verifyCode'];
14 
15 
16     // validate user input and redirect to the previous page if valid
17     if ($model->validate() && $model->login()) {
18         //以echo形式返回數據
19         echo CJSON::encode(array('type' => 'ok', 'msg' => '登錄的成功'));
20 
21     } else {
22         echo CJSON::encode(array('type' => 'no', 'msg' => '登錄失敗'));
23     }
24 
25 } 

 

 

  參考:ajax提交form表單資料詳細彙總jquery

相關文章
相關標籤/搜索