jQuery提交刷新页面 [英] jQuery Submit Refreshing Page
问题描述
以下代码旨在完成一个纯粹的ajax POST请求,相反,它似乎是通过ajax进行POST,然后浏览器导航到响应。
HTML ...
< div id =bin>
< form class =addmethod =postaction =/ bin / add />
< p>我很感兴趣!稍后保存。< / p>
< input type =hiddenname =product_idvalue =23423>
< input type =submitvalue =Save>
< / form>
< form style =display:none; class =removemethod =postaction =/ bin / remove />
< p>我改变了主意 - 我不感兴趣。< / p>
< input type =hiddenname =product_idvalue =23423>
< input type =submitvalue =Unsave>
< / form>
< / div>
jQuery ...
<$ p $ ($(this)).attr('action'),{
成功:函数(data){$(this).hide()。siblings('form')。show()},
data:$(this).serialize()
}) ;
return false;
})
据我所知, 返回false;
行应该表示无论如何,任何对submit函数的调用或者点击'Submit'按钮或者点击enter都意味着我的函数将执行浏览器将不会导航到 / bin / add
或 / bin / remove
。但出于某种原因,浏览器正在改变页面。
任何想法我在这里做错了?感谢。
我打赌是因为 $(this)
,尝试这种方式....
$('#bin form')。submit(function(){
$ $ this = $(this);
$ .post($ this.attr('action'),{
success:function(data){
$ this.hide ).siblings('form').show()
},
data:$ this.serialize()
$ b});
return false;
});
demo no error
demo 带有错误
The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false;
line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add
or /bin/remove
. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
my bet it's because of the $(this)
, try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
这篇关于jQuery提交刷新页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!