我对以下代码有一个奇怪的问题:
<script type="text/javascript">
$(document).ready(function(){
$('#loginSubmit').click(function () {
//start the ajax
var f = $("#loginForm");
request = $.ajax({
//this is the php file that processes the data
url: "app/index.php",
type: "POST",
data: f.serialize(),
dataType:"json",
cache: false
});
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
alert("fail")
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
alert("ok")
});
});
});
});
</script>
我正在使用firebug来调试代码,基本上在单击submit button
时,post请求没有收到任何响应,但是如果我然后使用firebug重新发送帖子数据那么一切正常吗?
有什么想法吗?
<form id="loginForm" action="" method="post" name="loginForm">
<h1>Login Form</h1>
<div>
<input type="text" placeholder="Email" required="" id="email" name="userEmail" />
</div>
<div>
<input type="password" placeholder="Password" required="" id="userPassword" name="userPassword" />
</div>
<div>
<input type="hidden" value="login" id="tag" name="tag" />
<input type="submit" value="Log in" id="loginSubmit" name="loginSubmit" />
<a href="#">Lost your password?</a>
</div>
</form>
答案 0 :(得分:1)
更改您的按钮类型,以防止默认提交 FORM
submit
至button
或者将点击的事件更改为提交
$('#loginform').submit(function(event){
event.preventDefault();
$.ajax({
//this is the php file that processes the data
url: $(this).attr("action"),
type: "POST",
data: $(this).serialize(),
dataType:"json",
cache: false
})
.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
})
.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: " + textStatus,
errorThrown
);
alert("fail");
})
.always(function () {
// callback handler that will be called regardless
// if the request failed or succeeded
// reenable the inputs
alert("ok");
});
});
答案 1 :(得分:1)
您的按钮在表单中的类型为submit
。默认操作是POST回服务器,导致回发。因此,您的AJAX很可能被取消。几个解决方案:
- 使用event
处理程序的click
属性和preventDefault
$('#loginSubmit').click(function (e) {
e.preventDefault();
...
});
来自点击方法的 - return false
$('#loginSubmit').click(function () {
...
return false;
});