您现在的位置是:首页 > 技术交流技术交流

jquery实现ajax提交form表单的方法

2015-02-07【技术交流】2552 人已围观

简介我们有一个非常普通的表单,但是需要ajax功能,今天特意初步研究了一下特写在此处以备查询 <form id=\"form1\" name...

我们有一个非常普通的表单,但是需要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)



关注宁波网站建设博客,更多精彩分享,敬请期待!
 

Tags:

很赞哦! ()

文章评论

点击排行

本站推荐

站点信息