A-A+
jQuery实现Ajax提交form表单的程序
Ajax提交form表单其实是非常的简单了,我们只要绑定触发事件就可以在用户点击时实现ajax提交表单了,下面一起来看一段jQuery实现Ajax提交form表单的程序
介绍:介绍了如何将一个普通的form表单,迅速改造成通过ajax方式提交,并将结果显示在对话框中。
正文:
我们有一个非常普通的表单:
- <form id="form1" name="form1" method="get" action="post.html">
- 标题<input id="testtitle" name="testtitle" type="text" size="40" />
- <input type="submit" value="提交">
- </form>
为了演示方便,method使用了get,可以根据需要改为post,现在我们把它改造成AJAX方式提交,方法很简单,只需要将下面的代码复制到页面中:
- <link type="text/css" href="jquery-ui.css" rel="stylesheet" />
- <style>
- #loading{background-image:url(images/loading.gif);background-position:0px 0px;background-repeat:no-repeat; position:absolute;width:50px;height:50px;top:60%;left:50%;margin-left:-25px;text-align:center;}
- </style>
- <script type ="text/javascript" src="jquery.js"></script>
- <script type ="text/javascript" src="jquery.form.js"></script>
- <script type="text/javascript" src="jquery-ui.js"></script>
- <script type="text/javascript">
- $(function () {
- bindSubmit();
- $("#loading").hide();
- $("#msgdlg").hide();
- });
- function bindSubmit() {
- var options = {
- target: '#msgdlg',
- success: showResponse,
- error: showError
- // 其它可选参数:
- //url: url // override for form's 'action' attribute
- //type: type // 'get' or 'post', override for form's 'method' attribute
- //dataType: null // 'xml', 'script', or 'json' (expected server response type)
- //clearForm: true // clear all form fields after successful submit
- //resetForm: true // reset the form after successful submit
- // $.ajax 选项,例如超时:
- //timeout: 3000
- };
- $('#form1').submit(function () {
- $(this).ajaxSubmit(options);
- $("#loading").show();
- return false;
- });
- }
- // 成功响应的回调函数
- function showResponse(responseText, statusText, xhr, $form) {
- $("#loading").hide();
- messagebox(responseText);
- }
- // 响应失败
- function showError(xhr, ajaxOptions, thrownError) {
- $("#loading").hide();
- messagebox("出错了!" + thrownError);
- }
- // 显示结果信息的对话框
- function messagebox(msg) {
- $("#msgdlg").html(msg);
- $("#dialog:ui-dialog").dialog("destroy");
- $("#msgdlg").dialog({
- modal: true,
- width: 380,
- height: 230,
- buttons: {
- 确认: function () {
- $(this).dialog("close");
- }
- }
- });
- }
- </script>
- <div id="msgdlg" title="消息"></div>
- <div id="loading" style="display:none" ondblclick="this.style.display='none'"></div>
代码中关键的几点:
(1)$('#form1').submit()对Form的Submit的绑定 (使用了jquery.form.js)
(2)定义的showResponse函数处理返回信息。
(3)$("#msgdlg").dialog()创建对话框并显示结果 (使用了jquery-ui.js)