Php ajaxpost第一次尝试失败
我对以下代码有一个wierd问题:Php ajaxpost第一次尝试失败,php,jquery,ajax,Php,Jquery,Ajax,我对以下代码有一个wierd问题: <script type="text/javascript"> $(document).ready(function(){ $('#loginSubmit').click(function () { //start the ajax var f = $("#loginForm"); request = $.ajax
<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>
更改按钮类型以防止默认提交表单
提交
至按钮
或者将您的点击事件更改为提交事件
$('#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");
});
});
您的按钮在表单中有一个类型
submit
。默认操作是回发到服务器,导致回发。您的AJAX很可能因此而被取消。有两种解决方案:
-使用单击处理程序的事件
属性,并预防默认值
$('#loginSubmit').click(function (e) {
e.preventDefault();
...
});
-从单击方法返回false
$('#loginSubmit').click(function () {
...
return false;
});
这是一个类型为“提交”的按钮吗?正确,对不起,我也会在那里添加我的html代码。很好,就是这样!谢谢,这很好很简单,为了教育的利益,为什么会这样?很抱歉,在我回复之前,编辑进入了,我正在回复更改的提交按钮?太好了。这是因为当时正在进行默认表单提交。您应该使用“event.preventDefault();”而不是“return false;”。我更改了你的答案。感谢编辑@Werner为什么“event.preventDefault()”比“return false”更好?你能解释一下吗
$('#loginSubmit').click(function () {
...
return false;
});