How to send dynamic key and value like in jQuery Ajax?

I want to send both a key and a value that will be dynamic (and the key will be dynamic, as when a user logs in). Then how to send a request. I want something like this:

var requestString;

if(something)
   requestString = "something";
else
   requestString= "else";

    jQuery.ajax({
                        url: handlerUrl,
                        dataType: "json",
                        data: {
                            requestString: request.term
                        }
                    });

Here, requestString is a variable and dynamically set. But for the current code. the key itself becomes "requestString", which must be dynamic. How to do it?

+5
source share
2 answers

Using

jQuery.ajax({
           url: handlerUrl,
           dataType: "json",
           data: requestString + '=' + request.term
      });
+3
source

create an object, press the dynamically generated key and the value on it .. and pass this object as data in ajax ..

try it

var requestString ;
 .....
dataString={};
dataString[requestString]=request.term

jQuery.ajax({
               url: handlerUrl,
               dataType: "json",
               data: dataString
          });
+2
source

All Articles