Ajax post serialize() does not include button name and value

前端 未结 3 2030
臣服心动
臣服心动 2020-11-29 10:10

My $.ajax() is not serializing the button name and value.

I have a very simple form. It has a button and a textbox.

相关标签:
3条回答
  • 2020-11-29 10:37

    jQuery's serialize() is pretty explicit about NOT encoding buttons or submit inputs, because they aren't considered to be "successful controls". This is because the serialize() method has no way of knowing what button (if any!) was clicked.

    I managed to get around the problem by catching the button click, serializing the form, and then tacking on the encoded name and value of the clicked button to the result.

    $("button.positive").click(function (evt) {
        evt.preventDefault();
    
        var button = $(evt.target);                 
        var result = button.parents('form').serialize() 
            + '&' 
            + encodeURI(button.attr('name'))
            + '='
            + encodeURI(button.attr('value'))
        ;
    
        console.log(result);
    });
    
    0 讨论(0)
  • 2020-11-29 10:38

    I like @slashingweapon 's approach, but why not even shorter, like this?

    $("button.positive").click(function () {
        var result = $(this).parents('form').serialize() 
            + '&' 
            + this.name
            + '='
            + this.value
        ;
        console.log(result);
    
        return false; // prevent default
    });
    

    Only if the server generates non-ascii button names or values, it would be like this:

    $("button.positive").click(function () {
        var result = $(this).parents('form').serialize() 
            + '&' 
            + encodeURI(this.name)
            + '='
            + encodeURI(this.value)
        ;
        console.log(result);
    
        return false; // prevent default
    });
    
    0 讨论(0)
  • 2020-11-29 10:50

    Here's a catch-all solution that will look for an input in the button's containing form. If it exists, it'll set the value, otherwise it will create a hidden input and set its value. This can also be useful if you're not wanting to submit the form immediately.

    $(document).on('click', '[name][value]:button', function(evt){
        var $button = $(evt.currentTarget),
            $input = $button.closest('form').find('input[name="'+$button.attr('name')+'"]');
        if(!$input.length){
            $input = $('<input>', {
                type:'hidden',
                name:$button.attr('name')
            });
            $input.insertAfter($button);
        }
        $input.val($button.val());
    });
    
    0 讨论(0)
提交回复
热议问题