javascript 通过ajax请求提交html表单?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11254884/
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
html form submission via an ajax request?
提问by Fallenreaper
Possible Duplicate:
jQuery AJAX submit form
可能重复:
jQuery AJAX 提交表单
I have a form on a page A, and instead of me posting to a new page, is there a way that i can do onSubmit ajax request it instead? I want to make the page to be able to load in the result into a div.
我在页面 A 上有一个表单,而不是我发布到一个新页面,有没有一种方法可以代替 onSubmit ajax 请求它?我想让页面能够将结果加载到 div 中。
I know how to write the script for the call sort of, but i wasn't sure if i had to hand write it or it if was possible to take all the form information and send it without having to code it all into the attributes. i was thinking I could just do some sort of thing like: onClick, post form but return results into a div.
我知道如何为呼叫编写脚本,但我不确定是否必须手写它,或者是否可以获取所有表单信息并发送它,而无需将其全部编码到属性中。我在想我可以做一些事情,比如:onClick,发布表单但将结果返回到一个 div 中。
Thoughts? Ideas?
想法?想法?
采纳答案by JROB
$.ajax({
url: 'mypage.html',
success: function(data){
$('.result').html(data);
},
error: function(){
alert('failure');
}
});
Then you have a div:
然后你有一个 div:
<div class="result"> </div>
This will automatically populate with the result of your ajax post.
这将自动填充您的 ajax 帖子的结果。
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.post/
Also see TONS of related questions: Jquery checking success of ajax post
另请参阅相关问题的大量内容:Jquery checks success of ajax post
回答by Rob d'Apice
Try using JQuery's serialize
(API ref here)
尝试使用 JQuery serialize
(API ref here)
EDIT: something like this:
编辑:像这样:
$("input.submit").click( function() {
$.ajax( {
type: "POST",
url: $("form").attr( 'action' ),
data: $("form").serialize(),
success: function( response ) {
//Code to process the response
}
});
return false;
} );