Advertisement
Guest User

Untitled

a guest
Aug 30th, 2015
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.50 KB | None | 0 0
  1. (function() {
  2. var makeRequest = function(url,callback,opt) {
  3. var xhr;
  4. if (XMLHttpRequest) { // Mozilla, Safari, ...
  5. xhr = new XMLHttpRequest();
  6. } else if (ActiveXObject) { // IE
  7. try {
  8. xhr = new ActiveXObject("Msxml2.XMLHTTP");
  9. }
  10. catch (e) {
  11. try {
  12. xhr = new ActiveXObject("Microsoft.XMLHTTP");
  13. }
  14. catch (e) {}
  15. }
  16. }
  17.  
  18. if (!xhr) {
  19. callback.call(this,
  20. 'Giving up :( Cannot create an XMLHTTP instance',
  21. null);
  22. return false;
  23. }
  24. xhr.onreadystatechange = function() {
  25. if (xhr.readyState === 4) {
  26. if (xhr.status === 200) {
  27. var data = xhr.responseText;
  28. if(opt && !opt.raw) {
  29. try {
  30. data = JSON.parse(data);
  31. } catch (e) {
  32. callback.call(this, e,null);
  33. return;
  34. }
  35. }
  36. callback.call(this,null,data);
  37. } else {
  38. callback.call(this,
  39. 'There was a problem with the request.',
  40. null);
  41. }
  42. }
  43. };
  44. var params = '';
  45. if (opt && opt.params && typeof(opt.params) == 'object') {
  46. for( var key in opt.params) {
  47. params += encodeURIComponent(opt.params[key]);
  48. }
  49. }
  50. var method = opt && opt.method ? opt.method : 'GET';
  51. if (method == 'GET') {
  52. url = params.length > 0 ? url+'?'+params : url;
  53. xhr.open('GET', url);
  54. xhr.send();
  55. } else if (method == 'POST') {
  56. var data = opt && opt.data ? opt.data : params;
  57. xhr.open('POST', url);
  58. xhr.send(JSON.stringify(data));
  59. }
  60. return xhr;
  61. }
  62.  
  63. if(typeof module !== 'undefined' && module.exports) {
  64. module.exports = makeRequest;
  65. }
  66. if(typeof window!== 'undefined') {
  67. window.getJSONData = makeRequest;
  68. }
  69. })();
  70.  
  71. var expect = require('chai').expect,
  72. getJSON = require('../'),
  73. sinon = require('sinon');
  74.  
  75. describe('get-json-data test the request', function() {
  76. beforeEach(function() {
  77. this.xhr = sinon.useFakeXMLHttpRequest();
  78. var requests = this.requests = [];
  79.  
  80. this.xhr.onCreate = function (xhr) {
  81. requests.push(xhr);
  82. };
  83. });
  84. afterEach(function() {
  85. this.xhr.restore();
  86. });
  87.  
  88. it('get json data', function() {
  89. var callback = sinon.spy();
  90. getJSON('/some/json', callback);
  91. expect(this.requests.length).to.equal(1);
  92. this.requests[0].respond(200,
  93. {"Content-Type": "application/json"},
  94. '{"id": 1, "name": "foo"}');
  95. sinon.assert.calledWith(callback, {"id": 1, "name": "foo"});
  96. });
  97. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement