Reputation: 4157
How to set a custom Ajax request header with jQuery has an excellent answer here.
So, if I do
var headervar='testvalue';
$.ajax({
type: "POST",
url: "foo.php",
headers:{'testname':headervar},
...
});
It nicely sets headers like
[Accept-Language] => en-US,en;q=0.5w-form-urlencoded;charset=UTF-8
[testname] => "testvalue"
[X-Requested-With] => XMLHttpRequest
...
However, I like to also set the header NAME. If it is hardcoded, like in the example above, it works OK. But if I do this with a variable
var headername='testname';
var headervar='testvalue';
$.ajax({
type: "POST",
url: "foo.php",
headers:{headername:headervar},
//...
});
The result is a header where the variablename suddenly becomes the headername.
[Accept-Language] => en-US,en;q=0.5w-form-urlencoded;charset=UTF-8
[headername] => "testvalue"
So the question: is it possible to set the headername as a variable in a jQuery Ajax request?
Upvotes: 3
Views: 1270
Reputation: 27765
You need to create temporary object for that and use bracket notation to define object property name from variable:
var headername='testname';
var headervar='testvar';
var headers_to_set = {};
headers_to_set[ headername ] = headervar;
$.ajax({
type: "POST",
url: "foo.php",
headers:header_to_set,
//...
});
Upvotes: 3