简体   繁体   中英

What is the best way to send many post parameters via ajax

I've been wondering on what is really the best way on sending so many parameters via Ajax jQuery.

I know how to send little number of post parameters via ajax, it would be like this :

$.ajax({
    type: "POST",
    url: 'controller/function',
    data: {
        param1 : param1, 
        param2 : param2
    },
    success: function (result) {

    }
});

And I've been wondering what if i will send 50 or up parameters. Let's say,

$.ajax({
    type: "POST",
    url: 'controller/function',
    data: {param1 : param1, param2 : param2, ......., param50 : param50},
    success: function (result) {

    }
});

Now if you'll ask why i need this, its because it is a requirement where i post different independent parameters . Leaving the requirement, i just want to know if this is ok or are there are any bad effects on this in terms of server side or client side?

Question no 2, what is the best approach you can recommend on sending many parameters in an Ajax call. Lets say i have 50 "DIFFERENT" long strings that i should post.

Any suggestions?

UPDATE :

Im not using form by the way. I am sending different long HTML strings and i send them not via form. I just grab them via jquery like

 var param1 = $(".divwrapper1").html(); 
 var param2 = $(".divwrapper2").html();
 ..... and so on and so for 

and use these variable and send it via ajax

I am assuming that you are submitting a large form. In this scenario its a good idea that you serialize your form data. A good way to check what happens in this process is as follows:

$( "form" ).on( "submit", function( event ) {
  event.preventDefault();
  console.log( $( this ).serialize() );
});

Take a look at => http://api.jquery.com/serialize/ for more info.

you are doing it the right way! however its more nice to build your post parameters outside the ajax call and serialize them so they can be send to the server in only one post parameter. If you don't serialize the data, all parameters will be send as different post variables.

var mydata={
    param1 : param1, 
    param2 : param2,
    param3 : param3, 
    param50 : param50
};

var myjson=JSON.stringify(mydata);


$.ajax({
    type: "POST",
    url: 'controller/function',
    data: {alldata: myjson}, //OR you could do: data: mydata,
    success: function (result) {

    }
});

on the server side you can receive your posted data (which is json in this case) by

$posteddata=$_POST['alldata'];//posteddata now contains the data as a string (json)

now you need to decode the received json string to make it an appropriate PHP type

$data= json_decode($posteddata);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM