码迷,mamicode.com
首页 > Web开发 > 详细

将form转为ajax提交的js代码

时间:2015-09-07 09:35:22      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:

在html中插入下面的代码:

函数ajaxSubmit是submit的ajax形式。

注意:这里面使用到了jquery库

            //<!--将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;
            }

            //<!--将form转为AJAX提交。-->        
       //<!--fn为返回后的回调函数,可以为空-->
function ajaxSubmit(frm, fn) { var dataPara = getFormJson(frm); var ajax_para={}; ajax_para[‘data‘]=dataPara; if (!frm.attr(‘action‘) ){ ajax_para[‘url‘]=this.location.pathname; } else{ ajax_para[‘url‘]=frm.attr(‘action‘); } ajax_para[‘type‘]=frm.attr(‘method‘); if (!frm.attr(‘method‘)){ ajax_para[‘type‘]=‘GET‘; } if (fn) { ajax_para[‘success‘]=fn; } htmlobj=$.ajax(ajax_para); return htmlobj; }

在form提交时候调用该插件

将form中submit按钮修改成

<button type="button" class="btn btn-default" onclick="ajaxSubmit($(‘form‘))">submit</button>

 

将form转为ajax提交的js代码

标签:

原文地址:http://www.cnblogs.com/yasmi/p/4787978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!