How do I modify serialized form data in jQuery?

前端 未结 4 807
你的背包
你的背包 2020-11-30 23:14

I am trying to submit my form in AJAX, so I have to serialize() the data. But I am using fckEditor and jQuery doesn\'t know how to deal with it, so after the se

4条回答
  •  难免孤独
    2020-12-01 00:04

    Here is a full jquery plugin based on @T.J's answer. You can call

    $('form#myForm').awesomeFormSerializer({
        foo: 'bar',
    })
    

    Which will replace or add the param 'foo' with value 'bar' (or any other param you add in the object)

    jQuery plugin :

    // Not builtin http://stackoverflow.com/a/5075798/2832282
    (function ( $ ) {
        // Pass an object of key/vals to override
        $.fn.awesomeFormSerializer = function(overrides) {
            // Get the parameters as an array
            var newParams = this.serializeArray();
    
            for(var key in overrides) {
                var newVal = overrides[key]
                // Find and replace `content` if there
                for (index = 0; index < newParams.length; ++index) {
                    if (newParams[index].name == key) {
                        newParams[index].value = newVal;
                        break;
                    }
                }
    
                // Add it if it wasn't there
                if (index >= newParams.length) {
                    newParams.push({
                        name: key,
                        value: newVal
                    });
                }
            }
    
            // Convert to URL-encoded string
            return $.param(newParams);
        }
    }( jQuery ));
    

提交回复
热议问题