jQuery .serializeObject is not a function - only i

2019-01-18 14:30发布

I'm using jQuery, and specifically this function

$("#postStatus").serializeObject();

It works absolutely fine in Chrome and Safari, but when I do it in Firefox it doesn't work. I used Firebug to see what error it was giving, and i'm getting this

$("#postStatus").serializeObject is not a function

Why doesn't this function work in Firefox?

UPDATE...

Oh yes, I completely forgot that it's not a core function. I remember that I searched a way to serialize a form and found this solution;

$.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;
};

I've managed to fix this issue by placing the function above at the top of the JS file. Thanks for your help guys.

3条回答
Evening l夕情丶
2楼-- · 2019-01-18 14:45

AFAIK jQuery has no function defined as serializeObject in its core. Probably you are using a plugin, and that its problematic in Firefox only so its safe to assume that your script inclusion is in proper order, try wrapping up your code in the ready handler

$(function(e){
$("#postStatus").serializeObject();
});

or you can place the javascript at the bottom of the page.

DEMO

查看更多
男人必须洒脱
3楼-- · 2019-01-18 14:48

You might also want to check this out https://github.com/citnvillareal/serializeObject.

Sample Usage

<form>
    <input type="text" name="txt01[][name]" value="Text 01" />
    <input type="text" name="txt01[][phone]" value="000001" />

    <input type="text" name="txt01[][name]" value="Text 02" />
    <input type="text" name="txt01[][phone]" value="000002" />

    <input type="submit" value="Submit" />
</form>

<script>
    ( function( $){
        $( document ).ready( function(){
            $( "form" ).submit( function( e ) {
                e.preventDefault();

                var jsonObject = $( this ).serializeObject();
                console.log( jsonObject );
            } );
        } );
    } )( jQuery );
</script>

Console Output

Object 
{
    txt01: Array(2) 
    {
        0: Object
        {
            name: Text 01
            phone: 000001
        },

        1: Object
        {
            name: Text 02
            phone: 000002
        }
    }
}

For more details click here.

查看更多
萌系小妹纸
4楼-- · 2019-01-18 15:00

Try serialize() or serializeArray() instead serializeObject()

查看更多
登录 后发表回答