Javascript 如何覆盖现有的 html 表单以使用 jquery 发布表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2967066/
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
How do you override an existing html form to use jquery to post the form?
提问by Chris
I have a simple form that I am currently posting back to the server to update a nickname. What jquery code do I add (without changing the form) so that the page will not refresh, but instead jquery will post the form in the background and then pop up an alert message containing the reply back from the server?
我有一个简单的表单,我目前正在发回服务器以更新昵称。我要添加什么 jquery 代码(不更改表单)以便页面不会刷新,而是 jquery 将在后台发布表单,然后弹出一条包含服务器回复的警报消息?
<form method="post" action="http://www.myserver.com/update_nickname" name="input">
Quick form to test update_nickname:<br>
New nickname:<input type="text" value="BigJoe" name="newNickname"><br>
<input type="submit" value="Submit">
</form>
<script src="jquery-1.4.2.min.js" type="text/javascript"> </script>
回答by Reigel
or
或者
$("form").submit(function(e){
var form = $(this);
$.ajax({
url : form.attr('action'),
type : form.attr('method'),
data : form.serialize(), // data to be submitted
success: function(response){
alert(response); // do what you like with the response
}
});
return false;
});
回答by Doug Neiner
You need to use jQuery to bind to the "submit" event and prevent the default action. It would be a little more efficient if your form and nickname input used id's in addition to their names:
您需要使用 jQuery 绑定到“提交”事件并阻止默认操作。如果您的表单和昵称输入id除了名称之外还使用's ,效率会更高一些:
<script type="text/javascript">
jQuery(function($){
$("form[name=input]").submit(function(e){
e.preventDefault(); // Keep the form from submitting
var form = $(this);
// Use the POST method to post to the same url as
// the real form, passing in newNickname as the only
// data content
$.post( form.attr('action'), { newNickname: form.find(':text').val() }, function(data){
alert(data); // Alert the return from the server
}, "text" );
});
});
</script>

