What to do with php after jquery .serialize()

后端 未结 3 764
慢半拍i
慢半拍i 2020-12-19 19:37

Ok somehow im having the hardest time figuring this out so i want to do an call ajax with a form and im using jquery to serialize it with .serialize(). The data being sent t

3条回答
  •  悲&欢浪女
    2020-12-19 20:00

    If you're submitting the form data with jQuery's Ajax functionality, there should not be a problem with using .serialize(). The server should see and urldecode automatically the POST content.

    As a demonstration, see this code:

    HTML



    POST Result

    
    

    jQuery

    $(document).ready(function(){
        $('pre').html($('#category-dynamic').serialize());
    
        $.post("http://jfcoder.com/test/processor.php", $('#category-dynamic').serialize(), function(data){
             $('pre').html($('pre').html()+"\n\n"+data);
        });
    });
    

    EDIT

    And the processor.php file contents:

    
    

    EDIT 2

    I think your error is that you're sending the content in such a way as to make the form data be a text string instead of url-encoded content.

    For instance, you could do this:

    var formSubmit = $(this).serialize() + "&formSubmit=true";
    $.post('ajax.php', formSubmit);
    

    And you'd have the same effect, and the server would be able to expand your POST variables without incident.

    EDIT 3

    See this example:

    Where the code is:

    $(document).ready(function(){
        var serial = $('#category-dynamic').serialize() + "&formSubmit=true";
        $('pre').html(serial);
        $.post("http://jfcoder.com/test/processor.php", serial, function(data){
             $('pre').html($('pre').html()+"\n\n"+data);
        });
    });
    

    Note the addition of the "&formSubmit=true" to the serial data. This outputs from the PHP page:

    POST Result
    
    category-name=&fields%5B%5D=&fields%5B%5D=&formSubmit=true
    
    Array
    (
        [category-name] => 
        [fields] => Array
            (
                [0] => 
                [1] => 
            )
    
        [formSubmit] => true
    )
    

    EDIT 4

    This uses the method you describe. See the difference?

    $(document).ready(function(){
        var serial = $('#category-dynamic').serialize();
        $('pre').html(serial);
        $.post("http://jfcoder.com/test/processor.php", {"formSubmit":"true","serial":serial}, function(data){
             $('pre').html($('pre').html()+"\n\n"+data);
        });
    });
    

    OUTPUT

    POST Result
    
    category-name=&fields%5B%5D=&fields%5B%5D=
    
    Array
    (
        [formSubmit] => true
        [serial] => category-name=&fields%5B%5D=&fields%5B%5D=
    )
    

提交回复
热议问题