Chr*_*ris 13 javascript ajax jquery
我有一个简单的表单,我目前正在发回服务器以更新昵称.我添加了什么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>
Run Code Online (Sandbox Code Playgroud)
Rei*_*gel 26
要么
$("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;
});
Run Code Online (Sandbox Code Playgroud)
您需要使用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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20737 次 |
| 最近记录: |