这是我的HTML
<form id="the_form">
Zip / Postal Code: <input id="zip" type="text" name="zip"><br/>
<input type="submit" value="Submit" id="submitButton">
</form>
<div id="output"></div>
这是我的jQuery
<script type="text/javascript">
$("document").ready(function() {
$("#submitButton").on("click",function(){
var value_to_send_to_php = $.trim($("#zip").val());
if(value_to_send_to_php != "") {
$.post("formphptoajax_rb.php", $("#the_form").serializeArray() , function(data) {
//#1 doesn't work here
});
//#2 doesn't work here
}
//#3 doesn't work here
});
$("#output").text("success");
});
</script>
上面的jQuery工作正常。也就是说,在点击submit
时,我得到了成功&#34; div
输出id&#34;输出&#34;。
当我将$("#output").text("success");
放在标记为#1,#2或#3的位置时,我无法理解为什么我不会得到相同的结果。
在#1和#2,我没有输出。在#3,我得到了成功&#34;几分之一秒然后就消失了。
答案 0 :(得分:2)
除了点击处理程序之外,页面也在提交,因为您点击了&#34;提交&#34;按钮。
使用输入类型=&#34;按钮&#34;代替。这就是它的设计目标:非提交按钮。
答案 1 :(得分:2)
您需要执行e.preventDefault()或从处理程序返回false。此外,您所拥有的内容将在加载时显示成功,而不是在单击按钮后显示。
答案 2 :(得分:1)
好的,让我们直截了当。 我想,$ .post调用AJAX异步回调(这很重要,因为如果你不想要ASYNC回调那么我很难理解你的问题而我的结论是错误的)。
<script type="text/javascript">
$("document").ready(function() {
$("#submitButton").on("click",function(){
var value_to_send_to_php = $.trim($("#zip").val());
if(value_to_send_to_php != "") {
// - ok, we have "#zip" value filled, so let's take "#the_form" data and sends them asynchronously to server
$.post("formphptoajax_rb.php", $("#the_form").serializeArray() , function(data) {
//#1 doesn't work here
// - great, our AJAX callback was successful, so we can inform user, that save or whatever operation was successfull
// - now we can process "data" returned from server
// - and we can show the success message - $("#output").text("success");
// BUT, all this will happen only, when you prevent page from full postback (which refresh the whole page)
});
//#2 doesn't work here
}
//#3 doesn't work here
// - in this place you have to prevent page from continue submitting (therefore full page postback is initiated)
// - so there should be "return false;" (without quotes of course)
// - or you can use "e.preventDefault();" here (as someone already mentioned), but in that case you have to change your click event handler signature from "function()" to "function(e)"
});
$("#output").text("success");
});
</script>
简化,单击提交按钮时调用postback - 浏览器获取表单数据并刷新页面(表单数据作为请求参数发送到服务器)。它是同步HTTP POST请求。好吧,术语“PostBack”主要用于ASP或ASP.NET。
截至“原始上下文在ajax完成时不存在” - 我的意思是,当你向服务器发送异步回调时,但是之后立即刷新页面(因为回发),那么原来的 异步回调的启动程序不再存在,并且没有例程可以处理该回调的结果(成功也不失败)。