ajax提交Form


Jquery的$.ajax方法可以实现ajax调用,要设置url,post,参数等。


如果要提交现有Form需要写很多代码,何不直接将Form的提交直接转移到ajax中呢。

<!DOCTYPE html>
<html>
<head>
    <title>form Ajax提交</title>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
    //将form转为AJAX提交
    function ajaxSubmit(frm, fn) {
        var dataPara = getFormJson(frm);
        $.ajax({
            url: frm.action,
            type: frm.method,
            data: dataPara,
            success: fn
        });
    }

    //将form中的值转换为键值对。
    function getFormJson(frm) {
        var o = {};
        var a = $(frm).serializeArray();
        $.each(a, function () {
            if (o[this.name] !== undefined) {
                if (!o[this.name].push) {
                    o[this.name] = [o[this.name]];
                }
                o[this.name].push(this.value || '');
            } else {
                o[this.name] = this.value || '';
            }
        });

        return o;
    }
//ajaxSubmit方法第一个参数,是要提交的form,第二个参数是ajax调用成功后的处理函数。
//将form的action传递给ajax的url,form的method传递给ajax的type,再将格式化后的表单内容传递给data。
//getFormJson方法将form的元素转化为json格式键值对。形如:{name:'aaa',password:'tttt'},注意将同名的放在一个数组里。
//调用
    $(document).ready(function(){
        $('#Form1').bind('submit', function(){
            ajaxSubmit(this, function(data){
                alert(data);
            });
            return false;
        });
        
        $('#Form2').bind('submit', function(){
            ajaxSubmit(this, function(data){
                alert(data);
            });
            return false;
        });
    });
</script> </head> <body> <form id="Form1" action="action.php" method="post" > 名称:<input name="name" type="text" /><br /> 密码:<input name="password" type="password" /><br /> 手机:<input name="mobile" type="text" /><br /> 说明:<input name="memo" type="text" /><br /> <input type="submit" value="提 交" /> </form> <form id="Form2" action="action.php" method="get" > 名称:<input name="name" type="text" /><br /> 密码:<input name="password" type="password" /><br /> 手机:<input name="mobile" type="text" /><br /> 说明:<input name="memo" type="text" /><br /> <input type="submit" value="提 交" /> </form> </body> </html>

在ajaxSubmit方法调用前,可验证数据是否正确,在alert(data)处可加入自己调用返回后处理代码。


在调用ajaxSubmit方法后,必须添加return false;语句防止Form真实提交。

 

 

posted @ 2015-05-14 14:25  壁虎漫步.  阅读(190)  评论(0编辑  收藏  举报