[英]How do you override an existing html form to use jquery to post the form?
我有一個簡單的表單,我目前正在發回服務器以更新昵稱。 我添加了什么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>
要么
$("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;
});
您需要使用jQuery綁定到“submit”事件並阻止默認操作。 如果您的表單和昵稱輸入除了名稱之外還使用了id
那么效率會更高一些:
<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>
這是一個插件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.