Jim Wu Jim Wu - 5 months ago 45
jQuery Question

Softcode Jquery Ajax Data Key

I am new to Javascript and Jquery and I'm trying to make a function for a flexible api call. What I'm wondering is: is there a way to soft code ajax Data keys?

For example:

var call = $.ajax({
url: url,
data: {Param: paramValue},
success: successFunction,
error: errorFunction
});


where
Param
is not an actual parameter in the api call like
url/api?Param=paramvalue
, rather a variable I had defined earlier like
Param = userInput()
. So that if the user enters
'metrics'
, I will call
url/api?metrics
.

If not, is there another way of doing this that I should be made aware of?

Thanks for your thoughts!

Answer

Well, you could use this way to define the data object :

var param = "metrics";
var data = {};
data[param] = "";
var call = $.ajax({
    url: url,
    data: data,
    success: successFunction,
    error: errorFunction
});
Comments