jQuery push()返回错误“undefined不是函数”

时间:2014-09-17 12:51:55

标签: javascript jquery arrays ajax object

此代码在提交表单时给出了错误“未定义不是第21行中的函数”而我不知道为什么

$.fn.serializeObject = function()
{
    var o = {};
    var a = this.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[name=dForm]").submit(function(ev){
        ev.preventDefault();
        var data = $(this).serializeObject();
        data.push({name:"bonjour",value:bonjour});

 // do something here ...

})

或者它必须是数组而不是对象?

1 个答案:

答案 0 :(得分:3)

serializeObject返回o,其在函数顶部定义为{}

push是Array对象的方法,而不是普通对象。它将一个项放在数组的末尾。

普通物体是无序的。将项目放在上面没有“结束”,因此有一个push方法没有意义。

您可能想要创建一个具有给定名称和值的新属性。

data.push({name:"bonjour",value:bonjour});

应该是

data.bonjour = bonjour;