jquery serialize and $.post

前端 未结 7 870
独厮守ぢ
独厮守ぢ 2020-12-01 12:32

I\'m trying to send a lot of data from a form using the $.post method in jQuery. I\'ve used the serialize() function first to make all the form data into one long string whi

相关标签:
7条回答
  • 2020-12-01 13:07

    So this is probably a bit obtuse, but I made a function to help me do this very thing since I got tired of making a bunch of fixes every time. serializeArray is kind of annoying because it provides a collection of objects, when all I wanted to have PhP reconstruct was an associative array. The function below will go through the serialized array and will build a new object with the appropriate properties only when a value exists.

    Firstly, the function (it takes the ID of the form in question):

    function wrapFormValues(form) { 
        form = "#" + form.attr("id") + " :input";
        form = $(form).serializeArray();
        var dataArray = new Object();
    
        for( index in form)
        {   
            if(form[index].value)   {
                dataArray[form[index].name] = form[index].value;    
            }
        }       
    
        return dataArray; 
    }
    

    When constructing my posts I also usually use an object since I usually tag on two or three other values before the form data and I think it looks cleaner than to define it inline, so the final step looks like this:

    var payload = new Object(); 
    //stringify requires json2.js from http://www.json.org/js.html
    payload.data = JSON.stringify(data);
    
    $.post("page.php", payload,  
        function(reply) {
            //deal with reply.
        });
    

    Server-side all you have to do is $payload = json_decode($_POST['data'], true) and you have yourself an associative array where the keys are the names of your form fields.

    Full disclaimer though, multiple-selects probably won't work here, you would probably only get whichever value was last on the list. This is also created very specifically to suit one of my projects, so you may want to tweak it to suit you. For instance, I use json for all of my replies from the server.

    0 讨论(0)
提交回复
热议问题