ajax提交form表单

  1. ajax提交form表单和不同的form表单的提交主要区别在于,ajax提交表单是异步提交的,而普通的是同步提交的表单。

  

  2. from视图部分

 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提交

 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)

  

 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表单资料详细汇总

 

 

 

posted @ 2016-04-25 23:16  JackMee  阅读(9325)  评论(0编辑  收藏  举报