Permalink
Browse files

Change XHR posting to send JSON as the body, and set the right conten…

…t type

Note that this means file uploads won't work anymore, and the server side has to be wise to receiving and parsing JSON.
  • Loading branch information...
1 parent 9c736c4 commit a49f26dbddede4b55d05e2e81cba600f329556ad @remy committed May 7, 2013
Showing with 8 additions and 12 deletions.
  1. +8 −12 xhr.js
View
20 xhr.js
@@ -1,6 +1,6 @@
function request(type, url, opts, callback) {
var xhr = new XMLHttpRequest(),
- fd;
+ pd;
if (typeof opts === 'function') {
callback = opts;
@@ -10,29 +10,25 @@ function request(type, url, opts, callback) {
xhr.open(type, url);
if (type === 'POST' && opts) {
- fd = new FormData();
+ pd = JSON.stringify(opts);
- for (var key in opts) {
- fd.append(key, JSON.stringify(opts[key]));
- }
+ xhr.setRequestHeader('Content-Type', 'application/json');
}
- xhr.setRequestHeader('x-requested-with', 'XMLHttpRequest');
+ xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onload = function () {
- callback(null, JSON.parse(xhr.response));
+ callback.call(xhr, null, JSON.parse(xhr.response));
};
xhr.onerror = function () {
- callback(true);
+ callback.call(xhr, true);
};
- xhr.send(opts ? fd : null);
-
+ xhr.send(opts ? pd : null);
+
return xhr;
}
var get = request.bind(this, 'GET');
var post = request.bind(this, 'POST');
-
-// usage: get('/foo', function (err, data) { ... })

0 comments on commit a49f26d

Please sign in to comment.