Jquery : ajax 提交Form

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

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

以前的处理方法

如Form代码如下:

<formid="Form1" action="action.aspx" method="post" >

名称:<inputname="name" type="text" /><br/>

密码:<inputname="password" type="password" /><br/>

手机:<inputname="mobile" type="text" /><br/>

说明:<inputname="memo" type="text" /><br/>

<inputtype="submit" value="提 交" />

</form> 

当提交后,会跳转到action.aspx页面。并可以通过Request.Params["name"]可以取到值。

   //将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;
    }
    function save_RoomOrder() {
        var dataPara = getFormJson($('#Form1'));
        LG.ajax({
            loading: '正在保存数据中...',
            type: "AjaxHotelManage",
            method: "Tts_Hotel_RoomOrder",
            data: dataPara,
            success: function () {
                //dg.curWin.f_reload();
                dg.curWin.LG.tip('保存成功!');               
            },
            error: function (message) {
                LG.tip(message );
            }
        });
    }

save_RoomOrder方法第一个参数,是要提交的form,再将格式化后的表单内容传递给data。

getFormJson方法将form的元素转化为json格式键值对。形如:{name:'aaa',password:'tttt'},注意将同名的放在一个数组里。

原文地址:https://www.cnblogs.com/Fooo/p/2551038.html