Javascript 防止页面重新加载和重定向表单提交 ajax/jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26567486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prevent page reload and redirect on form submit ajax/jquery
提问by Vettan Maximillion
I have looked through all the similar posts out there but nothing seems to help. This is what I have
我已经浏览了所有类似的帖子,但似乎没有任何帮助。这就是我所拥有的
HTML:
HTML:
<section>
<form id="contact-form" action="" method="post">
<fieldset>
<input id="name" name="name" placeholder="Name" type="text" />
<input id="email" name="email" placeholder="Email" type="text" />
<textarea id="comments" name="comments" placeholder="Message"></textarea>
<div class="12u">
<a href="#" id="form-button-submit " class="button" onClick="sendForm()">Send Message</a>
<a href="#" id="form-button-clear" class="button" onClick="document.getElementById('contact-form').reset()">Clear Form</a>
</div>
<ul id="response"></ul>
</fieldset>
</form>
</section>
JavaScript/jQuery:
JavaScript/jQuery:
function sendForm() {
var name = $('input#name').val();
var email = $('input#email').val();
var comments = $('textarea#comments').val();
var formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
}); // end ajax
}
What I am unable to do is prevent the page refresh when the #form-button-submitis pressed. I tried return false;I tried preventDefault()and every combination including return false;inside the onClick. I also tried using input type="button"and type="submit"instead and same result. I can't solve this and it is driving be nuts. If at all possible I would rather use the hyperlink due to some design things.
I would really appreciate your help on this.
我无法做的是在#form-button-submit按下时阻止页面刷新。我想return false;我试图preventDefault()和每一个组合,包括return false;里面的onClick。我也尝试使用input type="button"andtype="submit"代替,结果相同。我无法解决这个问题,它正在开车疯了。如果可能的话,由于某些设计原因,我宁愿使用超链接。我真的很感激你在这方面的帮助。
回答by What have you tried
Modify the function like this:
修改函数如下:
function sendForm(e){
e.preventDefault();
}
And as comment mentions, pass the event:
正如评论所提到的,传递事件:
onclick = sendForm(event);
Update 2:
更新 2:
$('#form-button-submit').on('click', function(e){
e.preventDefault();
var name = $('input#name').val(),
email = $('input#email').val(),
comments = $('textarea#comments').val(),
formData = 'name=' + name + '&email=' + email + '&comments=' + comments;
$.ajax({
type: 'post',
url: 'js/sendEmail.php',
data: formData,
success: function(results) {
$('ul#response').html(results);
}
});
});
回答by Samuel Cook
function sendForm(){
// all your code
return false;
}
回答by stf
Have you tried using
你有没有试过使用
function sendForm(event){
event.preventDefault();
}
回答by Kaif Khan
I was also bit engaged in finding solution to this problem, and so far the best working method I found was this-
我也有点忙于寻找这个问题的解决方案,到目前为止,我发现的最好的工作方法是——
Try using XHR to send request to any url, instead of $.ajax()...I know it sounds bit weird but try it out!
Example-
尝试使用 XHR 向任何 url 发送请求,而不是 $.ajax()...我知道这听起来有点奇怪,但试试吧!
例子-
<form method="POST" enctype="multipart/form-data" id="test-form">
var testForm = document.getElementById('test-form');
testForm.onsubmit = function(event) {
event.preventDefault();
var request = new XMLHttpRequest();
// POST to any url
request.open('POST', some_url, false);
var formData = new FormData(document.getElementById('test-form'));
request.send(formData);
This would send your data successfully ...without page reload.
这将成功发送您的数据......无需重新加载页面。
回答by firstmadcoding
Simple and Complete working code
简单完整的工作代码
<script>
$(document).ready(function() {
$("#contact-form").submit(function() {
$("#loading").show().fadeIn('slow');
$("#response").hide().fadeOut('slow');
var frm = $('#contact-form');
$.ajax({
type: frm.attr('method'),
url: 'url.php',
data: frm.serialize(),
success: function (data) {
$('#response').html(data);
$("#loading").hide().fadeOut('slow');
$("#response").slideDown();
}, error: function(jqXHR, textStatus, errorThrown){
console.log(" The following error occured: "+ textStatus, errorThrown );
} });
return false;
});
});
</script>
#loadingcould be an image or something to be shown when the form is processing, to use the code simply create a form with ID contact-form
#loading可以是图像或在处理表单时显示的内容,使用代码只需创建一个带有 ID 的表单 contact-form
回答by John
Another way to avoid the form from being submitted is to place the button outside of the form. I had existing code that was working and created a new page based on the working code and wrote the html like this:
避免表单被提交的另一种方法是将按钮放在表单之外。我有正在运行的现有代码,并根据工作代码创建了一个新页面,并像这样编写了 html:
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
</form>
This form cause the undesirable redirect described above. Changing the html to what is shown below fixed the problem.
这种形式会导致上述不受欢迎的重定向。将 html 更改为下面显示的内容修复了问题。
<form id="getPatientsForm">
Enter URL for patient server
<br/><br/>
<input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
<input name="patientRootUrl" size="100"></input>
<br/><br/>
</form>
<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>
回答by Ahmed Mabrouk
I expect anyone to understand my idea very well as it's a very simple idea.
我希望任何人都能很好地理解我的想法,因为这是一个非常简单的想法。
give your required form itself an id or you can get it by any other way you prefer.
in the form input "submit" call an onclick method from your javascript file.
in this method make a variable refer to your from id the addEventListener on it and make a preventDefault method on "submit" not on "click".
To clarify that see this:// element refers to the form DOM after you got it in a variable called element for example: element.addEventListener('submit', (e) => { e.preventDefault(); // rest of your code goes here });The idea in brief is to deal with the form by submit event after dealing with submit button by click event.
为您所需的表单本身提供一个 ID,或者您可以通过任何其他您喜欢的方式获取它。
在表单输入“提交”中调用您的 javascript 文件中的 onclick 方法。
在这个方法中,让一个变量从 id 引用你的 addEventListener 并在“提交”而不是“点击”上创建一个 preventDefault 方法。
为了澄清这一点,请参阅:// element refers to the form DOM after you got it in a variable called element for example: element.addEventListener('submit', (e) => { e.preventDefault(); // rest of your code goes here });简而言之,就是通过点击事件处理提交按钮后,再通过提交事件处理表单。
Whatever is your needs inside this method, it will work now without refresh :)
Just be sure to deal with ajax in the right way and you will be done.
无论您在此方法中有什么需求,它现在无需刷新即可工作:)
只要确保以正确的方式处理 ajax,您就可以完成。
Of course it will work only with forms.
当然,它只适用于表单。
回答by Yashas
The way I approached this: I removed the entire formtag and placed all the form elements such as input, textarea tags inside a divand used one button to call a javascript function. Like this:
我的处理方式是:我删除了整个form标签,并将所有表单元素(例如 input、textarea 标签)放在 a 中,div并使用一个按钮来调用 javascript 函数。像这样:
<div id="myform">
<textarea name="textarea" class="form-control">Hello World</textarea>
<button type="submit" class="btn btn-primary"
onclick="javascript:sendRequest()">Save
changes</button>
<div>
Javascript:
Javascript:
function sendRequest() {
$.ajax({
type: "POST",
url: "/some/url/edit/",
data: {
data: $("#myform textarea").val()
},
success: function (data, status, jqXHR) {
console.log(data);
if (data == 'success') {
$(`#mymodal`).modal('hide');
}
}
});
return true;
}
I thought why use a formwhen we are sending the actual request using AJAX. This approach may need extra effort to do things like resetting the form elements but it works for me.
我想为什么form在我们使用 AJAX 发送实际请求时使用 a 。这种方法可能需要额外的努力来完成诸如重置表单元素之类的事情,但它对我有用。
Note: The above answers are more elegant than this but my use case was a little different. My webpage had many forms and I didn't think registering event listeners to every submit button was a good way to go. So, I made each submit button call the sendRequest() function.
注意:上面的答案比这更优雅,但我的用例有点不同。我的网页有很多表单,我不认为为每个提交按钮注册事件监听器是一个好方法。所以,我让每个提交按钮都调用了 sendRequest() 函数。

