While working on implementing a simple xhr abstraction, I encountered a warning when trying to set the headers for a POST request. Strangely, I noticed that the issue might be related to setting the headers in a separate JavaScript file. This is because when I tried setting the headers within the <script>
tag in the .html file, everything worked smoothly. The POST request itself functioned properly, but the warning persisted and I was curious about the reason behind it.
The warning specifically appeared for both the content-length
and connection
headers, but only in WebKit browsers such as Chrome 5 beta and Safari 4. Interestingly, Firefox did not show any warnings. Although the Content-Length header displayed the correct value, the Connection header was being set to keep-alive instead of close. This led me to believe that Firefox may have been disregarding my setRequestHeader calls and generating its own headers. Unfortunately, I have yet to test this code in Internet Explorer. Below, you can find the markup and code snippets:
test.html
:
<!DOCTYPE html>
<html>
<head>
<script src="jsfile.js"></script>
<script>
var request = new Xhr('POST', 'script.php', true, 'data=somedata', function(data) {
console.log(data.text);
});
</script>
</head>
<body>
</body>
</html>
jsfile.js
:
function Xhr(method, url, async, data, callback) {
var x;
if(window.XMLHttpRequest) {
x = new XMLHttpRequest();
x.open(method, url, async);
x.onreadystatechange = function() {
if(x.readyState === 4) {
if(x.status === 200) {
var responseData = {
text: x.responseText,
xml: x.responseXML
};
callback.call(this, responseData);
}
}
}
if(method.toLowerCase() === "post") {
x.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
x.setRequestHeader("Content-Length", data.length);
x.setRequestHeader("Connection", "close");
}
x.send(data);
} else {
// ... implement IE code here ...
}
return x;
}