Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /// <reference path="../libs/jquery-1.11.1.min.js" />
- var httpModule = (function () {
- function makeHttpRequest(resourceUrl, header, data) {
- var getHttpRequest,
- httpRequest,
- deferred = $.Deferred(),
- statusType,
- response;
- getHttpRequest = (function () {
- var xmlHttpFactories;
- xmlHttpFactories = [
- function () {
- return new XMLHttpRequest();
- }, function () {
- return new ActiveXObject("Msxml3.XMLHTTP");
- }, function () {
- return new ActiveXObject("Msxml2.XMLHTTP.6.0");
- }, function () {
- return new ActiveXObject("Msxml2.XMLHTTP.3.0");
- }, function () {
- return new ActiveXObject("Msxml2.XMLHTTP");
- }, function () {
- return new ActiveXObject("Microsoft.XMLHTTP");
- }
- ];
- return function () {
- var xmlFactory, _i, _len;
- for (_i = 0, _len = xmlHttpFactories.length; _i < _len; _i++) {
- xmlFactory = xmlHttpFactories[_i];
- try {
- return xmlFactory();
- } catch (_error) {
- }
- }
- return null;
- };
- })();
- httpRequest = getHttpRequest();
- httpRequest.onreadystatechange = function () {
- if (httpRequest.readyState === 4) {
- statusType = parseInt(httpRequest.status / 100);
- if (statusType === 2) {
- response = JSON.parse(httpRequest.response);
- deferred.resolve(response);
- } else {
- deferred.reject('Something went wrong');
- }
- }
- };
- httpRequest.open(header, resourceUrl, true);
- httpRequest.setRequestHeader('Content-Type', 'application/json');
- httpRequest.setRequestHeader('Accept', 'application/json');
- httpRequest.send(data);
- return deferred.promise();
- }
- function getJSON(url) {
- return makeHttpRequest(url, 'GET', null);
- }
- function postJSON(url, data) {
- data = JSON.stringify(data);
- return makeHttpRequest(url, 'POST', data)
- }
- return {
- getJSON: getJSON,
- postJSON: postJSON,
- };
- })();
- var url = 'http://localhost:3000/students';
- httpModule.postJSON(url,
- {
- name: 'LOL',
- grade: 5
- })
- .then(function (data) {
- if (data) {
- console.log(data);
- }
- }, function (error) {
- if (error) {
- console.log(error);
- }
- })
- .done();
- httpModule.getJSON(url)
- .then(function (data) {
- if (data) {
- console.log(data);
- }
- }, function (error) {
- if (error) {
- console.log(error);
- }
- })
- .done();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement