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)


source to share

3 answers

It doesn't depend on jQuery, it's just vanilla JavaScript.

You have to do this:

var objToSend = {};
objToSend["param1"] = "value1";
objToSend["param2"] = "value2";

$.get('link/to/send', objToSend, function(result) {
    // ... etc




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




Try it. You just create your dynamic data and call the function with your dynamic data as an argument.

function sendRequest(data)
   $.get('link/to/send',data, function(result) { /* code here*/ });




All Articles