jsbeans

jsbeans  1.0.0

jsbeans > jsbeans > Request.js (source view)
Search:
 
Filters
/*!
 * Copyright (c) 2009 Francesco Mele jsbeans@francescomele.com
 *
 * This Software is licenced under the LGPL Licence (GNU Lesser General 
 * Public License).
 * In addition to the LGPL Licence the Software is subject to the 
 * following conditions:
 * 
 * 	i	every modification must be public and comunicated to the Author
 * 	ii	every "jsbean" added to this library must be self consistent 
 * 		except for the dependence from jsbeans-x.x.x.js
 * 	iii	copyright notice and this permission notice shall be included 
 * 		in all copies or substantial portions of the Software
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */
/**
 * Utility to manage urls, request parameters and AJAX calls.
 * @namespace jsbeans
 * @class Request
 * @static
 */
jsbeans.Request = {
	/**
	 * @method getRequestObject
	 * @return {XmlHttpRequest}
	 * @static
	 * */
	getRequestObject: function() {
		var res = null;
		try	{
			res = new XMLHttpRequest();
		} 
		catch (e) {
			try	{ 
				res = new ActiveXObject("Msxml2.XMLHTTP");
			} 
			catch (e) {
				try { 
					res = new ActiveXObject("Microsoft.XMLHTTP");
				} 
				catch (e) {
					alert("Your browser does not support AJAX!");
				}
			}
		}
		return res;
	},
	/**
	 * AJAX call via <code>GET</code> method.
	 * @method GET
	 * @param url {String} the url to GET. It appends a new parameter on every call to prevent browser's cache.
	 * @param callback {Function} the callback with <code>responseText</code> and <code>XmlHttpRequest</code> itself as arguments.
	 * @static
	 * */
	GET: function(url, callback) {
		var lsXmlHttp = jsbeans.Request.getRequestObject();
		if (lsXmlHttp == null) {
			return;
		}
		lsXmlHttp.onreadystatechange = function() {
			if (lsXmlHttp.readyState == 4) {
				setTimeout(function() {
					callback(lsXmlHttp.responseText, lsXmlHttp);
				}, 500);
			}
		};
		// check if url has been already filled with some parameters
		if (url.indexOf("?") != -1) {
			url = url + "&";
		} 
		else {
			url = url + "?";
		}
		// append a random number as a way to prevent browser's cache
		if (jsbeans.Request.QUERY_STRING == "") {
			url = url + new Date().getTime();
		} 
		else {
			url = url + jsbeans.Request.QUERY_STRING + "&" + new Date();
		}
		lsXmlHttp.open("GET", url, true);
		lsXmlHttp.send(null);
	},
	/**
	 * AJAX call via <code>POST</code> method.<br/>
	 * {@param} <code class="param">data</code> may be omitted in favour of {@param} <code class="param">callback</code> passed directly as second argument.
	 * @method POST
	 * @param url {String}
	 * @param data {String} it will be passed 'as is' on the <code>send</code>.
	 * @param callback {Function} the callback with <code>responseText</code> and <code>XmlHttpRequest</code> itself as arguments.
	 * @static
	 * */
	POST: function(url, data, callback) {
		// "courtesy" of jquery
		var isFun = function(fn) {
			return !!fn && typeof fn != "string" && !fn.nodeName && 
				fn.constructor != Array && /function/i.test( fn + "" );
		};
		var dt = null;
		var callbak = function(){};
		if (arguments.length == 2) {
			callbak = arguments[1];
		} 
		else if (arguments.length == 3) {
			if (isFun(arguments[1])) {
				dt = null;
				callbak = arguments[1];
			} 
			else {
				dt = arguments[1];
				callbak = arguments[2];
			}
		}
		
		var lsXmlHttp = jsbeans.Request.getRequestObject();
		if (lsXmlHttp == null) {
			return;
		}
		lsXmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		lsXmlHttp.onreadystatechange = function() {
			if (lsXmlHttp.readyState == 4) {
				setTimeout(function() {
					callbak(lsXmlHttp.responseText, lsXmlHttp);
				}, 500);
			}
		};
		lsXmlHttp.open("POST", url, true);
		lsXmlHttp.send(dt);
	},
	/**
	 * If you want to directly call a <code>send</code>.
	 * @method send
	 * @param xhr {XmlHttpRequest} you may use <code class="methd">jsbeans.Request.getRequestObject()</code>
	 * @param callback {Function} the callback with <code>responseText</code> and <code>XmlHttpRequest</code> itself as arguments.
	 * @static
	 * */
	send: function(xhr, callback) {
		xhr.onreadystatechange = function() {
			if (xhr.readyState == 4) {
				setTimeout(function() {
					callback(xhr.responseText, xhr);
				}, 500);
			}
		};
		xhr.send(null);
	},
	/**
	 * Returns the (URI decoded) value of the {@param} <code class="param">parameterName</code> for the current url or <code>null</code> otherwise.
	 * @method getParameter
	 * @param parameterName {String}
	 * @return {String}
	 * @static
	 * */
	getParameter: function(parameterName) {
		if (jsbeans.Request.QUERY_STRING.length == 0) {
			return null;
		}
		var qs = jsbeans.Request.QUERY_STRING.replace(/\+/g, ' ');
		var items = qs.split('&');
		for (var i = 0, item; item = items[i]; i++) {
			var p = item.split('=');
			var n = decodeURIComponent(p[0]);
			if (parameterName == n) {
				return (p.length == 2) ? decodeURIComponent(p[1]) : null;
			}
		}
		return null;
	},
	/**
	 * Returns the (URI decoded) value of the {@param} <code class="param">parameterName</code> for the current hash supposed in the form of GET urls (e.g. <code>#par1=one&par2=two</code>) or <code>null</code> otherwise.
	 * @method getHashParameter
	 * @param parameterName {String}
	 * @return {String}
	 * @static
	 * */
	getHashParameter: function(parameterName) {
		var hash = jsbeans.Request.getHash();
		if (hash != null) {
			var qs = hash.replace(/\+/g, ' ');
			var items = qs.split('&');
			for (var i = 0, item; item = items[i]; i++) {
				var p = item.split('=');
				var n = decodeURIComponent(p[0]);
				if (parameterName == n) {
					return (p.length == 2) ? decodeURIComponent(p[1]) : null;
				}
			}
		}
		return null;
	},
	/**
	 * Checks if current url contains a {@param} <code class="param">parameterName</code> parameter.
	 * @method containsParameter
	 * @param parameterName {String}
	 * @return {boolean}
	 * @static
	 * */
	containsParameter: function(parameterName) {
		return jsbeans.Request.getParameter(parameterName) != null;
	},
	/**
	 * The hash is an anchor portion of current url. E.g. <code>&lt;a href="index.html#this_is_a_hash">some link&lt/a></code>
	 * @method getHash
	 * @return {String} current hash value ('#' excluded) or <code>null</code>
	 * @static
	 * */
	getHash: function() {
		return location.hash ? location.hash.substring(1) : null;
	},
	/**
	 * The context path is the base url of a site. This is the javascript way to get it.<br/>
	 * Note that some DNS rules may conflict with this method.<br/>
	 * It uses <code>window.location.pathname</code>.
	 * @method getContextPath
	 * @return {String}
	 * @static
	 * */
	getContextPath: function() {
		return window.location.pathname.substring(0, window.location.pathname.indexOf("/", 1));
	}
};

/**
 * The current query string (parameter name-value pairs)
 * @property jsbeans.Request.QUERY_STRING
 * @type {String}
 * @static
 * @final
 * */
jsbeans.Request.QUERY_STRING = location.search.substring(1, location.search.length);

Copyright © 2016 Francesco Mele. All rights reserved.