JSFiddle - React, Tailwind, and code Playground
by jsumners
HTML
<p>
<input id="ipBtn" type="button" value="Get IP">
<input id="timeBtn" type="button" value="Get Time">
<input id="echoBtn" type="button" value="Echo">
</p>
<p>The problem being shown here is that $.ajax is not correctly setting up requests with the options given:</p>
<ol>
<li>If `dataType: "jsonp"` is set then the `headers` option seems to be ignored (also the `type` option, but that isn't shown here).</li>
<li>If the `dataType` option is not specified, and the remote host supports CORS, then the custom header name is added to the Access-Control-Request-Headers header as a value instead of as an actual header.</li>
</ol>
CSS
p {
margin: 5px 15px;
}
ol {
list-style: decimal;
margin: 35px;
}
li {
margin: 5px 0;
}
JavaScript
var myObj = {},
$ipBtn = $('#ipBtn'),
$timeBtn = $('#timeBtn'),
$echoBtn = $('#echoBtn');
// Basically a custom $.ajaxSetup
myObj.ajax = function(options, service) {
var _options = {
url: "http://json.itcouldbe9.com/" + service, dataType: "jsonp",
dataType: "jsonp",
headers: {
"x-custom-header": "foobar"
}
};
for (var option in options) {
if (!options.hasOwnProperty(option)) {
continue;
}
_options[option] = options[option];
}
$.ajax(_options);
};
// We expect this to send a "x-custom-header" header with the request
// since it uses myObj.ajax to perform the request.
$ipBtn.on('click', function() {
myObj.ajax({
success: function(data) {
alert(data.ip);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
}, 'ip');
});
// We expect this to also send a "x-custom-header" header because
// we directly add the headers property to a stanard $.ajax
// call.
$timeBtn.on('click', function() {
$.ajax({
url: "http://json.itcouldbe9.com/time",
dataType: "jsonp",
headers: {
"x-custom-header": "barbaz"
},
success: function(data) {
alert(data.time);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
// This is actually adding our custom header, but as a value to another
// header?
$echoBtn.on('click', function() {
$.ajax({
url: "http://json.itcouldbe9.com/echo",
data: {"answer": 42},
headers: {
"x-custom-header": "panic"
},
success: function(data) {
alert("answer = " + data.answer);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});