Comparing version 1.0.3 to 1.0.4
{ | ||
"name": "xhr-tool", | ||
"version": "1.0.3", | ||
"version": "1.0.4", | ||
"description": "XMLHttpRequest with Promises", | ||
"keywords": [ "xhr", "promises", "es6" ], | ||
"author": "Jannes Meyer <jannes.meyer@gmail.com> (http://jannesmeyer.com/)", | ||
"author": "Jannes Meyer <jannes.meyer@gmail.com>", | ||
"license": "GPLv3", | ||
@@ -8,0 +8,0 @@ "repository": "JannesMeyer/xhr-tool", |
@@ -7,2 +7,6 @@ # xhr-tool | ||
Install the package like this: | ||
npm install xhr-tool | ||
**Import the function** | ||
@@ -14,2 +18,4 @@ | ||
Needs a browser that supports Promises or a Promise polyfill. | ||
## getJSON | ||
@@ -20,1 +26,9 @@ | ||
Sends an asynchronous request and returns a Promise for the parsed JSON response | ||
Example usage: | ||
~~~js | ||
getJSON('http://www.nactem.ac.uk/software/acromine/dictionary.py?sf=BMI').then(function(obj) { | ||
console.log(obj); | ||
}); | ||
~~~ |
@@ -6,21 +6,25 @@ /** | ||
var res = Promise.defer(); | ||
var req = new XMLHttpRequest(); | ||
req.onload = function() { | ||
try { | ||
res.resolve(JSON.parse(req.response)); | ||
} catch (err) { | ||
res.reject(err); | ||
} | ||
}; | ||
req.onerror = function() { | ||
res.reject(new Error('Error ' + req.status)); | ||
}; | ||
req.ontimeout = function() { | ||
res.reject(new Error('Request timeout')); | ||
}; | ||
req.open('GET', url); | ||
req.setRequestHeader('Accept', 'application/json'); | ||
req.send(); | ||
if (typeof XMLHttpRequest !== 'undefined') { | ||
var req = new XMLHttpRequest(); | ||
req.onload = function() { | ||
try { | ||
res.resolve(JSON.parse(req.response)); | ||
} catch (err) { | ||
res.reject(err); | ||
} | ||
}; | ||
req.onerror = function() { | ||
res.reject(new Error('Error ' + req.status)); | ||
}; | ||
req.ontimeout = function() { | ||
res.reject(new Error('Request timeout')); | ||
}; | ||
req.open('GET', url); | ||
req.setRequestHeader('Accept', 'application/json'); | ||
req.send(); | ||
} else { | ||
res.reject(new Error('XMLHttpRequest not available')); | ||
} | ||
return res; | ||
} | ||
exports.getJSON = getJSON; |
2446
42
32