views:

44

answers:

2

right now in my $.ajax({ ..}); call I have the following option:

data: { param0: param0, param1: param1}

Say I want the number of parameters to by dynamic (based on a variable passed to the function in which the ajax call is made). How do I provide data: a dynamic set of parameters? I think I need to somehow construct an object (?) ahead of time (i.e. before the ajax call) and then pass this object to data:..but I'm not sure how to do this.

By variable passed in, I mean optional parameters which will be used as the GET params: param2 and param3 if they are passed in. So:

function myAjaxCall(param0, param1, param2, param3) { // param2/3 are optional
  $.ajax({
      //...
      data: { param0: param0, param1: param1} // this will need param2/3 if passed in
      //..
  });
}

So depending on if param2 and param3 are passed in (either, none or both is valid) I need the data object constructed accordingly.

+1  A: 

As you mentioned you need to make an object out of your parameters and pass it as data:

var mydata = {
    name: 'ali',
    email: '[email protected]',
    ...
}

$.ajax({
    ...
    data: mydata,
    ...
});
Ali Sattari
+1  A: 

You should make use of the automatically created arguments array.

function myAjaxCall() {
 $.ajax({
   data: arguments, // "arguments" is an Array Object created automatically by JS
   ...
 });
}

or, if you want it to be an object literal with the arguments array as a property:

function myAjaxCall() {
 $.ajax({
   data: {args: arguments}, // "arguments" is an Array Object 
    ...                     //   created automatically by JS
 });
}

You can call this with any number of parameters, and the parameters can be any data form.

myAjaxCall({ fruit: "apple"}, "blah", 500, true);

Note that arguments is read only, so if you want to work with it, you have to copy it, and arguments.splice(0) will not work.... you have to use a for loop.

To check how many arguments were passed in, simply look at arguments.length.

Peter Ajtai
This is great, but lots of frameworks (I know ASP.Net) have trouble with arrays for JSON parameters, you are better off passing an object with a property that is the array. Granted, the array is valid JSON, I know, but in practice it's much more of a pain to deal with.
sworoc
@sworoc - Then just add the array to an object.
Peter Ajtai
Which is what I said at the end of my first sentence, glad we agree! :)
sworoc
@sworoc - Edited to include that form too.
Peter Ajtai