jQuery将form表单的数据封装成json对象

  /**
     * 自动将form表单封装成json对象
     */
    $.fn.serializeObject = function() {
        var o = {};
        var a = this.serializeArray();
        $.each(a, function() {
            if (o[this.name]) {
                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;
    };
//ajax请求,以json格式
  $.ajax({
            url:"buy",
            type:"POST",
            data:JSON.stringify($('form').serializeObject()),
            contentType:"application/json",  //缺失会出现URL编码,无法转成json对象
            success:function(){
                alert("成功");
            }
        });

猜你喜欢

转载自www.cnblogs.com/longailong/p/12066379.html