JQuery.post or .get pass dynamic parameters
The general way to send a request to the server is
$.get('link/to/send', {
param1: "value1",
param2: "value2"
}, function(result) {
// ... etc
});
Now if I want to send the names of dynamic parameters, can jQuery support? (i.e. I need to write some generic code so I can specify parameter names at runtime)
Yes, it can be done using parenthesis notation. You can access the properties of an object using the square bracket ( []
) as if you were accessing the values โโof the array.
In your case, the code might look like this:
//Name of the parameters
var str1 = "param1";
var str2 = "param2";
//Create an empty object
var obj = {};
//Set the values of the parameters.
obj[str1] = "value1";
obj[str2] = "value2";
//Send the GET request.
$.get('link/to/send', obj, function(result) {
// ... etc
});
This code should be synonymous with the code in your question. It sends one parameter named param1
with value value1
and one named param2
with value value2
.
source to share