ajax提交form表单

时间:2021-08-02 02:56:41

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

  

  2. from视图部分

 <form id="loginForm" name="loginForm" action="admin/user/login" method="post">
<table align="center">
<tr>
<td>用户名:</td>
<td colspan="2"><input type="text" name="username" id="username" /></td>
</tr>
<tr>
<td>密 码:</td>
<td colspan="2"><input type="password" name="password" id="password" /></td>
</tr>
<td colspan="3" align="center">
<input id="login_submit_button" type="submit" value="登录"/>
</td>
</tr>
</table>
16 </form>

  3. ajax提交

 //加载js
<script src = "../js/jquery-1.4.min.js" type = "text/javascript"></script>
<script type = "text/javascript">
$('#loginForm').on('submit', function (e){
e . preventDefault();
$.ajax( {
type : "POST",
dataType: "json",
url : 'url',
data : $(this) . serialize(),
success : function (res) {
console . log(res)
if (res . type == 'ok') {
alert(res . msg);
//成功后跳转路由设置
window . location . href = '';
} else {
if (res . type == "no") {
alert(res . msg);
}
}
}
});
});
</script>

  4. 后台处理(php)

  

 //首先判是否有ajax提交
if (!Yii::app()->request->isAjaxRequest)
{
Yii::app()->end();
} $model = new XXX; if (isset($_POST['FrontLogin'])) {
//像一般的form提交取值
$model->username = $_POST['FrontLogin']['username'];
$model->password = md5($_POST['FrontLogin']['password']);
$model->verifyCode = $_POST['LoginForm']['verifyCode']; // validate user input and redirect to the previous page if valid
if ($model->validate() && $model->login()) {
//以echo形式返回数据
echo CJSON::encode(array('type' => 'ok', 'msg' => '登陆的成功')); } else {
echo CJSON::encode(array('type' => 'no', 'msg' => '登陆失败'));
} }

  参考:ajax提交form表单资料详细汇总