我正在尝试使用Ajax和jQuery创建帖子。
但它不起作用。它只刷新当前页面。
HTML :
<form name="update_text_post" action="" id="update_text_post" method="post">
<textarea name="textbox" class="textbox" maxlength="600"></textarea>
<input type="submit" name="submit" value="Update" class="update_post_submit">
</form>
jQuery :
$('#update_text_post').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
return false
});
e.preventDefault();它不工作..它实际上甚至没有执行MYSQL查询。好像它甚至没有发送表单或定位post_ajax2.php文件。
答案 0 :(得分:2)
您需要使用 .preventDefault()
来停止页面重新加载时的默认表单提交行为。
$(function() {
$('#update_text_post').submit(function(e) {
e.preventDefault(); // e.preventDefault() for prevent form submisson with page reload
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
答案 1 :(得分:1)
// 1. you missed $ here, so it will not be a dom ready callback.
// your case is just define a function, and without executing it.
$(function () {
$('#update_text_post').submit(function (e) {
// 2. you need to prevent the default submit event.
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function (html) {
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
function afterSuccess() {
$('#update_text_post').resetForm(); // reset form
close_box();
}
答案 2 :(得分:0)
您必须停止提交按钮的默认行为(表单发布)。否则表单将再次提交,您将再次看到页面加载(您将不会注意到ajax带给您页面的更改 - 某些部分页面更新)。您可以使用preventDefault功能执行此操作。
$(function(){
$('#update_text_post').submit(function(e) {
e.preventDefault(); // prevent the default submit behaviour
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
});
答案 3 :(得分:0)
您必须在函数中调用e.preventDefault();
以阻止表单提交。
$('#update_text_post').submit(function(e) {
// prevent form submit
e.preventDefault();
$.ajax({
type: "POST",
url: "post_ajax2.php",
data: dataString,
cache: false,
success: function(html)
{
$("#wallwrap").prepend(html);
close_box();
$('#update_text_post').resetForm();
}
});
});
答案 4 :(得分:0)
添加return false
。
$('#update_text_post').submit(function(e) {
$.ajax({
...
})
return false;
});
答案 5 :(得分:0)
点击提交按钮即可 - 它提交表单。如果要使用AJAX POST请求替换表单提交,则需要通过阻止该事件的默认行为来停止提交表单(以及重新加载页面)。
您可以通过在绑定到submit事件处理程序的回调函数末尾调用return false;
,或者将对事件的引用传递给回调函数并调用e.preventDefault()
(其中{ {1}}指的是事件)。
这两种方法的主要区别在于,{j}回调函数中的e
也会阻止事件冒泡。在这种情况下,这并不是什么大不了的事。