我不知道今晚发生了什么,但我似乎无法让AJAX正常工作。提交表单时,它会使用URL中的值刷新页面。我正在使用具有提交处理程序的验证插件,但它仍然会刷新。我之前使用过这种方法并没有遇到任何问题。看看这里的页面,让我知道你的想法:
http://www.jacobsmits.com/demos/jquery_ajax.html?firstName=&lastName=&email=&message=&contactSubmit=
<div class="demo_content" style="display:none">
<form id="contact_form">
<span class="inputSpan">
<input value="" class="input input1" title="First name" id="firstName" name="firstName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Last name" id="lastName" name="lastName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Email" id="email" name="email" type="text" />
</span>
<span class="inputSpan">
<textarea type="text" id="message" name="message" title="Message" class="input textArea" ></textarea>
</span>
<span class="inputSpan">
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</span>
<div id="contact_ajax_wrap">
<div id="contact_ajax_gif" style="display:none;"><img src="http://www.jacobsmits.com/images/main/ajax-loader-black.gif" width="32" height="32" /></div>
<div id="contact_ajax_success" style="display:none">Thanks! I'll get back to you shortly.</div>
</div>
</form>
<script type="text/javascript">
//This script will handle the email form
$(window).load(function() {
$('#contact_form').placeholderRX({textColor: '#999', hoverColor: '#FBFBFB', addClass: 'yourFormInputText'});
});
$(".button").click(function() {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
});
</script>
答案 0 :(得分:2)
您需要取消提交按钮的默认行为(提交表单不是ajax)。
可以使用事件对象上的preverntDefault()
或return false;
$(".button").click(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});
有一个提交事件,所以最好先听一下这个事件而不是点击按钮:
$("#contact_form").submit(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});
答案 1 :(得分:1)
您需要取消submit
按钮
$(".button").click(function(e) {
e.preventDefault();
//rest of your code here
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({