Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Versions 1.0

Added JSONP support for cross-domain requests.
  • Loading branch information...
commit 2e3f63393d81ef9e93d20a1ed723611289525783 1 parent e0bbc0a
Kyle Barrow authored
Showing with 81 additions and 35 deletions.
  1. +10 −6 README.md
  2. +1 −1  chibi-min.js
  3. +70 −28 chibi.js
16 README.md
View
@@ -1,4 +1,4 @@
-# Chibi v0.9.2
+# Chibi v1.0
#### A tiny JavaScript micro-framework
@@ -397,13 +397,15 @@ If only the *html* argument is specified, this will replace the inner HTML of th
</html>
```
-#### $(selector).ajax(url,*method*,*callback*,*nocache*)
-*Sends an AJAX request, optionally firing a callback with the XHR `responseText` on success*
+#### $(selector).ajax(url,*method*,*callback*,*nocache*,*nojsonp*)
+*Sends an AJAX request, optionally firing a callback with the XHR `responseText` and `status`*
-**ajax** uses the GET method if none is specified. When *nocache* is true, a `_ts` time stamp is added to the URL to prevent caching, yes, I'm looking at you Android Browser.
+**ajax** uses the GET method if none is specified. When *nocache* is true, a `_ts` time stamp is added to the URL to prevent caching, yes, I'm looking at you Android Browser and iOS 6.
**ajax** supports JSON as a selector ({'name','value'}), useful for when you want to send data without using form field DOM elements.
+For cross-domain requests, **ajax** uses JSONP by default but this can be overridden if *nojsonp* is true. JSONP requests will apply any *callback* to `callback=?` or similar in the **ajax** url. The *method* is obviously always `GET` for JSONP request.
+
```html
<!DOCTYPE html>
<html>
@@ -416,8 +418,10 @@ If only the *html* argument is specified, this will replace the inner HTML of th
</form>
<script>
$('form').ajax('ajax.html'); // XHR all form data using "GET" to "ajax.html"
- $({'text':'Foo Bar'}).ajax('ajax.html'); // XHR the JSON using "GET" to "ajax.html"
- $('form').ajax('ajax.html',"POST",function(data){alert(data)},true); // XHR all form data using "POST" to "ajax.html", alerts results on success, adds a cache busting time stamp
+ $({text:'Foo Bar'}).ajax('ajax.html'); // XHR the JSON using "GET" to "ajax.html"
+ $('form').ajax('ajax.html',"POST",function(data,status){ },true); // XHR all form data using "POST" to "ajax.html", returns responseText and status, adds a cache busting time stamp
+ $({sort:'created',direction:'asc'}).ajax('https://api.github.com/users/kylebarrow/repos?callback=?','GET',function(data,status){ }); // JSONP
+
</script>
</body>
</html>
2  chibi-min.js
View
@@ -1 +1 @@
-/*Chibi v0.9.2, (C)2012 Kyle Barrow, MIT licensed*/(function(){"use strict";function Q(){var e;V=t;for(e=0;e<W[n];e+=1)W[e]();W=[]}function G(){var e;$=t;V||Q();for(e=0;e<X[n];e+=1)X[e]();X=[]}function Y(e,t){var r;for(r=t[n]-1;r>=0;r-=1)e(t[r])}function Z(e){return e[o](/-\w/g,function(e){return e.charAt(1)[u]()})}function et(e,t){return e[a]?e[a][Z(t)]:K[f]?K[f](e,l).getPropertyValue(t):l}function tt(e,t){return encodeURIComponent(e)[o](/%20/g,"+")+"="+encodeURIComponent(t)[o](/%20/g,"+")}function nt(r){var i=[],s=[],o=e,u;if(r)if(r.nodeType&&r.nodeType===1)i=[r];else if(typeof r=="object"||typeof r[n]=="number"&&typeof r.item===c){o=t;i=r}else if(typeof r===h){J[p]||(J[p]=function(e){var t,r=J[d]("head")[0],i,s=[],o;t=J[v]("STYLE");t.type="text/css";if(t[m]){t[m][g]=e+" {a:b}";r.appendChild(t);i=J[d]("*");for(o=0;o<i[n];o+=1)et(i[o],"a")==="b"&&s[y](i[o]);r[b](t)}return s});i=J[p](r)}if(o)s=i;else for(u=0;u<i[n];u+=1)s[u]=i[u];return s}function rt(e,t,n){try{e[w][Z(t)]=n}catch(r){}}function it(e){e[w][E]="";et(e,E)===S&&(e[w][E]="block")}function st(e){e=e.reverse();e[n]===1&&(e=e[0]);return e}function ot(e){var t="",r,i,s;if(e[x]===Object){for(r in e)if(e.hasOwnProperty(r))if(e[r][x]===Array)for(i=0;i<e[r][n];i+=1)t+=T+tt(r,e[r][i]);else t+=T+tt(r,e[r])}else Y(function(e){if(e[N]==="FORM")for(i=0;i<e.elements[n];i+=1){r=e.elements[i];if(!r.disabled)switch(r.type){case"button":case"image":case"file":case"submit":case"reset":break;case"select-one":r[n]>0&&(t+=T+tt(r[C],r[k]));break;case"select-multiple":for(s=0;s<r[n];s+=1)r[s][L]&&(t+=T+tt(r[C],r[s][k]));break;case A:case O:r[M]&&(t+=T+tt(r[C],r[k]));break;default:t+=T+tt(r[C],r[k])}}},e);return t[n]>0?t.substring(1):""}function ut(a){var f=nt(a);return{ready:function(e){e&&(V?e():W[y](e))},loaded:function(e){e&&($?e():X[y](e))},loop:function(e){typeof e===c&&Y(function(t){e(t)},f)},find:function(t){if(t){var r=[],i;switch(t){case"first":f[n]>0&&(f=[f.shift()]);break;case"last":f[n]>0&&(f=[f.pop()]);break;case"odd":case"even":for(i=t==="odd"?0:1;i<f[n];i+=2)r[y](f[i]);f=r}}return f[n]>0?f[n]===1?f[0]:f:e},hide:function(){Y(function(e){e[w][E]=S},f)},show:function(){Y(function(e){it(e)},f)},toggle:function(){Y(function(e){et(e,E)===S?it(e):e[w][E]=S},f)},remove:function(){var e=f[n];Y(function(e){try{e[_][b](e)}catch(t){}},f);f=[]},css:function(e,t){var r=[];Y(function(n){t?rt(n,e,t):n[w][Z(e)]?r[y](n[w][Z(e)]):et(n,e)?r[y](et(n,e)):r[y](l)},f);if(r[n]>0)return st(r)},cls:function(r,i){var s=[],u,a,l,c,h;if(r){u=r.split(/\s+/);i=i||o}Y(function(f){a=f[D];if(r){switch(i){case"add":f[D]=a+" "+r;break;case o:f[D]=r;break;case P:case H:case"remove":c=t;for(h=0;h<u[n];h+=1){l=new RegExp("\\b"+u[h]+"\\b","g");if(i===P){if(!a.match(l)){c=e;break}}else i===H?f[D]=f[D].match(l)?f[D][o](l,""):f[D]+" "+u[h]:f[D]=f[D][o](l,"")}i===P&&s[y](c)}f[D]=f[D][o](/^\s+|\s+$/g,"")}else s[y](a)},f);if(s[n]>0)return st(s)},html:function(e,t){var r=[],i,s;Y(function(n){if(t){i=J[v]("div");i[B]=e;while((s=i.lastChild)!==l)try{t==="before"?n[_][j](s,n):t==="after"&&n[_][j](s,n.nextSibling)}catch(o){break}}else e?n[B]=e:r[y](n[B])},f);if(r[n]>0)return st(r)},attr:function(e,t){var r=[];Y(function(n){if(e){e=e.toLowerCase();switch(e){case w:t?n[w][g]=t:n[w][g]?r[y](n[w][g]):r[y](l);break;case"class":t?n[D]=t:n[D]?r[y](n[D]):r[y](l);break;default:t?n.setAttribute(e,t):n[F](e)?r[y](n[F](e)):r[y](l)}}},f);if(r[n]>0)return st(r)},val:function(r){var i=[],s=[],o,u,a,c;typeof r===h&&(r=[r]);Y(function(f){if(r)switch(f[N]){case I:for(o=0;o<f[n];o+=1)for(u=0;u<r[n];u+=1){f[o][L]="";if(f[o][k]===r[u]){f[o][L]=L;break}}break;case q:switch(f.type){case A:case O:f[M]="";for(o=0;o<r[n];o+=1)if(f[k]===r[o]){f[M]=M;break}break;default:f[k]=r[0]}break;case R:case U:f[k]=r[0]}else switch(f[N]){case I:c=s[n];s[y]([]);for(o=0;o<f[n];o+=1)f[o][L]&&s[c][y](f[o][k]);switch(s[c][n]){case 0:s[c]=l;break;case 1:s[c]=s[c][0]}break;case q:switch(f.type){case A:f[M]?s[y](f[k]):s[y](l);break;case O:a=e;for(o=0;o<i[n];o+=1)if(i[o][0]===f[C]){f[M]&&(s[i[o][1]]=f[k]);a=t}if(!a){i[y]([f[C],s[n]]);f[M]?s[y](f[k]):s[y](l)}break;default:s[y](f[k])}break;case R:case U:s[y](f[k])}},f);if(s[n]>0)return st(s)},on:function(t,n,s){if(a===K||a===J)f=[a];Y(function(o){J[r]?s?o.removeEventListener(t,n,e):o[r](t,n,e):J[i]&&(s?o.detachEvent("on"+t,n):o[i]("on"+t,n))},f)},ajax:function(e,n,r,i){var o,a=ot(f),l=e.indexOf("?")===-1?"?":T,c="_ts="+ +(new Date);n=n||"GET";K.XMLHttpRequest?o=new XMLHttpRequest:K.ActiveXObject&&(o=new ActiveXObject("Microsoft.XMLHTTP"));if(o){n=n[u]();n==="GET"&&(e+=l+a);i&&(e+=n===z?l+c:T+c);o.open(n,e,t);n===z&&o.setRequestHeader("Content-Type","application/x-www-form-urlencoded");o.send(a);o[s]=function(){if(o.readyState===4&&o.status===200&&r)try{r(o.responseText)}catch(e){}}}}}}var e=!1,t=!0,n="length",r="addEventListener",i="attachEvent",s="onreadystatechange",o="replace",u="toUpperCase",a="currentStyle",f="getComputedStyle",l=null,c="function",h="string",p="querySelectorAll",d="getElementsByTagName",v="createElement",m="styleSheet",g="cssText",y="push",b="removeChild",w="style",E="display",S="none",x="constructor",T="&",N="nodeName",C="name",k="value",L="selected",A="checkbox",O="radio",M="checked",_="parentNode",D="className",P="has",H="toggle",B="innerHTML",j="insertBefore",F="getAttribute",I="SELECT",q="INPUT",R="TEXTAREA",U="BUTTON",z="POST",W=[],X=[],V=e,$=e,J=document,K=window;if(J[r]){J[r]("DOMContentLoaded",Q,e);K[r]("load",G,e)}else if(J[i]){J[i](s,Q);K[i]("onload",G)}else K.onload=G;K.$=ut})();
+/*Chibi v1.0, (C)2012 Kyle Barrow, MIT Licensed.*/(function(){"use strict";function Z(){var e;K=t;for(e=0;e<$[n];e+=1)$[e]();$=[]}function et(){var e;Q=t;K||Z();for(e=0;e<J[n];e+=1)J[e]();J=[]}function tt(e,t){var r;for(r=t[n]-1;r>=0;r-=1)e(t[r])}function nt(e){return e[u](/-\w/g,function(e){return e.charAt(1)[a]()})}function rt(e,t){return e[f]?e[f][nt(t)]:Y[l]?Y[l](e,c).getPropertyValue(t):c}function it(e,t){return encodeURIComponent(e)[u](/%20/g,"+")+"="+encodeURIComponent(t)[u](/%20/g,"+")}function st(r){var i=[],s=[],o=e,u;if(r)if(r.nodeType&&r.nodeType===1)i=[r];else if(typeof r=="object"||typeof r[n]=="number"&&typeof r.item===h){o=t;i=r}else if(typeof r===p){G[d]||(G[d]=function(e){var t,r=G[v](m)[0],i,s=[],o;t=G[g]("STYLE");t.type="text/css";if(t[y]){t[y][b]=e+" {a:b}";r[w](t);i=G[v]("*");for(o=0;o<i[n];o+=1)rt(i[o],"a")==="b"&&s[E](i[o]);r[S](t)}return s});i=G[d](r)}if(o)s=i;else for(u=0;u<i[n];u+=1)s[u]=i[u];return s}function ot(e,t,n){try{e[x][nt(t)]=n}catch(r){}}function ut(e){e[x][T]="";rt(e,T)===N&&(e[x][T]="block")}function at(e){e=e.reverse();e[n]===1&&(e=e[0]);return e}function ft(e){var t="",r,i,s;if(e[C]===Object){for(r in e)if(e.hasOwnProperty(r))if(e[r][C]===Array)for(i=0;i<e[r][n];i+=1)t+=k+it(r,e[r][i]);else t+=k+it(r,e[r])}else tt(function(e){if(e[L]==="FORM")for(i=0;i<e.elements[n];i+=1){r=e.elements[i];if(!r.disabled)switch(r.type){case"button":case"image":case"file":case"submit":case"reset":break;case"select-one":r[n]>0&&(t+=k+it(r[A],r[O]));break;case"select-multiple":for(s=0;s<r[n];s+=1)r[s][M]&&(t+=k+it(r[A],r[s][O]));break;case _:case D:r[P]&&(t+=k+it(r[A],r[O]));break;default:t+=k+it(r[A],r[O])}}},e);return t[n]>0?t.substring(1):""}function lt(f){var l=st(f);return{ready:function(e){e&&(K?e():$[E](e))},loaded:function(e){e&&(Q?e():J[E](e))},loop:function(e){typeof e===h&&tt(function(t){e(t)},l)},find:function(t){if(t){var r=[],i;switch(t){case"first":l[n]>0&&(l=[l.shift()]);break;case"last":l[n]>0&&(l=[l.pop()]);break;case"odd":case"even":for(i=t==="odd"?0:1;i<l[n];i+=2)r[E](l[i]);l=r}}return l[n]>0?l[n]===1?l[0]:l:e},hide:function(){tt(function(e){e[x][T]=N},l)},show:function(){tt(function(e){ut(e)},l)},toggle:function(){tt(function(e){rt(e,T)===N?ut(e):e[x][T]=N},l)},remove:function(){var e=l[n];tt(function(e){try{e[H][S](e)}catch(t){}},l);l=[]},css:function(e,t){var r=[];tt(function(n){t?ot(n,e,t):n[x][nt(e)]?r[E](n[x][nt(e)]):rt(n,e)?r[E](rt(n,e)):r[E](c)},l);if(r[n]>0)return at(r)},cls:function(r,i){var s=[],o,a,f,c,h;if(r){o=r.split(/\s+/);i=i||u}tt(function(l){a=l[B];if(r){switch(i){case"add":l[B]=a+" "+r;break;case u:l[B]=r;break;case j:case F:case"remove":c=t;for(h=0;h<o[n];h+=1){f=new RegExp("\\b"+o[h]+"\\b","g");if(i===j){if(!a.match(f)){c=e;break}}else i===F?l[B]=l[B].match(f)?l[B][u](f,""):l[B]+" "+o[h]:l[B]=l[B][u](f,"")}i===j&&s[E](c)}l[B]=l[B][u](/^\s+|\s+$/g,"")}else s[E](a)},l);if(s[n]>0)return at(s)},html:function(e,t){var r=[],i,s;tt(function(n){if(t){i=G[g]("div");i[I]=e;while((s=i.lastChild)!==c)try{t==="before"?n[H][q](s,n):t==="after"&&n[H][q](s,n.nextSibling)}catch(o){break}}else e?n[I]=e:r[E](n[I])},l);if(r[n]>0)return at(r)},attr:function(e,t){var r=[];tt(function(n){if(e){e=e.toLowerCase();switch(e){case x:t?n[x][b]=t:n[x][b]?r[E](n[x][b]):r[E](c);break;case"class":t?n[B]=t:n[B]?r[E](n[B]):r[E](c);break;default:t?n.setAttribute(e,t):n[R](e)?r[E](n[R](e)):r[E](c)}}},l);if(r[n]>0)return at(r)},val:function(r){var i=[],s=[],o,u,a,f;typeof r===p&&(r=[r]);tt(function(l){if(r)switch(l[L]){case U:for(o=0;o<l[n];o+=1)for(u=0;u<r[n];u+=1){l[o][M]="";if(l[o][O]===r[u]){l[o][M]=M;break}}break;case z:switch(l.type){case _:case D:l[P]="";for(o=0;o<r[n];o+=1)if(l[O]===r[o]){l[P]=P;break}break;default:l[O]=r[0]}break;case W:case X:l[O]=r[0]}else switch(l[L]){case U:f=s[n];s[E]([]);for(o=0;o<l[n];o+=1)l[o][M]&&s[f][E](l[o][O]);switch(s[f][n]){case 0:s[f]=c;break;case 1:s[f]=s[f][0]}break;case z:switch(l.type){case _:l[P]?s[E](l[O]):s[E](c);break;case D:a=e;for(o=0;o<i[n];o+=1)if(i[o][0]===l[A]){l[P]&&(s[i[o][1]]=l[O]);a=t}if(!a){i[E]([l[A],s[n]]);l[P]?s[E](l[O]):s[E](c)}break;default:s[E](l[O])}break;case W:case X:s[E](l[O])}},l);if(s[n]>0)return at(s)},on:function(t,n,s){if(f===Y||f===G)l=[f];tt(function(o){G[r]?s?o.removeEventListener(t,n,e):o[r](t,n,e):G[i]&&(s?o.detachEvent("on"+t,n):o[i]("on"+t,n))},l)},ajax:function(e,n,r,i,f){var h,p=ft(l),d=e.indexOf("?")===-1?"?":k,y=new RegExp("http[s]?://(.*?)/","gi"),b=y.exec(e),E="_ts="+ +(new Date),x=G[v](m)[0],T="Chibi"+ +(new Date),N;if(!f&&b&&Y.location.host!==b[1]){e+=d+p;i&&(e+=k+E);if(r&&e.indexOf("=?")!==-1){e=e[u]("=?","="+T);Y[T]=function(e){try{r(e,200)}catch(t){}}}N=document[g]("script");N.async="async";N.src=e;N[o]=function(){x[S](N)};x[w](N)}else{n=n||"GET";Y.XMLHttpRequest?h=new XMLHttpRequest:Y.ActiveXObject&&(h=new ActiveXObject("Microsoft.XMLHTTP"));if(h){n=n[a]();if(n==="GET"){e+=d+p;p=c}i&&(e+=n===V?d+E:k+E);h.open(n,e,t);h[s]=function(){if(h.readyState===4&&r)try{r(h.responseText,h.status)}catch(e){}};n===V&&h.setRequestHeader("Content-Type","application/x-www-form-urlencoded");h.send(p)}}}}}var e=!1,t=!0,n="length",r="addEventListener",i="attachEvent",s="onreadystatechange",o="onload",u="replace",a="toUpperCase",f="currentStyle",l="getComputedStyle",c=null,h="function",p="string",d="querySelectorAll",v="getElementsByTagName",m="head",g="createElement",y="styleSheet",b="cssText",w="appendChild",E="push",S="removeChild",x="style",T="display",N="none",C="constructor",k="&",L="nodeName",A="name",O="value",M="selected",_="checkbox",D="radio",P="checked",H="parentNode",B="className",j="has",F="toggle",I="innerHTML",q="insertBefore",R="getAttribute",U="SELECT",z="INPUT",W="TEXTAREA",X="BUTTON",V="POST",$=[],J=[],K=e,Q=e,G=document,Y=window;if(G[r]){G[r]("DOMContentLoaded",Z,e);Y[r]("load",et,e)}else if(G[i]){G[i](s,Z);Y[i](o,et)}else Y[o]=et;Y.$=lt})();
98 chibi.js
View
@@ -1,4 +1,4 @@
-/*Chibi v0.9.2, Copyright (C) 2012 Kyle Barrow
+/*Chibi v1.0, Copyright (C) 2012 Kyle Barrow
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
@@ -676,55 +676,97 @@ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLI
}, nodes);
},
// Basic XHR 1, no file support. Shakes fist at IE
- ajax: function (url, method, callback, nocache) {
+ ajax: function (url, method, callback, nocache, nojsonp) {
var xhr,
query = serializeData(nodes),
querystart = (url.indexOf('?') === -1) ? '?' : '&',
- timestamp = '_ts=' + (+new Date());
+ hostsearch = new RegExp('http[s]?://(.*?)/', 'gi'),
+ domain = hostsearch.exec(url),
+ timestamp = '_ts=' + (+new Date()),
+ head = d.getElementsByTagName('head')[0],
+ jsonpcallback = 'Chibi' + (+new Date()),
+ script;
- method = method || 'GET';
- if (w.XMLHttpRequest) {
- xhr = new XMLHttpRequest();
- } else if (w.ActiveXObject) {
- xhr = new ActiveXObject('Microsoft.XMLHTTP'); // IE < 9
- }
+ // JSONP if cross domain url
+ if (!nojsonp && domain && w.location.host !== domain[1]) {
- if (xhr) {
- method = method.toUpperCase();
+ url += querystart + query;
- if (method === 'GET') {
- url += querystart + query;
+ if (nocache) {
+ url += '&' + timestamp;
}
- if (nocache) {
- url += (method === 'POST') ? querystart + timestamp : '&' + timestamp;
+ // Replace jsonp ? with callback
+ if (callback && url.indexOf('=?') !== -1) {
+
+ url = url.replace('=?', '=' + jsonpcallback);
+
+ w[jsonpcallback] = function (data) {
+ try {
+ callback(data, 200);
+ } catch (e) {}
+ };
}
- // Douglas Crockford: "Synchronous programming is disrespectful and should not be employed in applications which are used by people"
- xhr.open(method, url, true);
+ script = document.createElement('script');
+ script.async = 'async';
+ script.src = url;
+
+ script.onload = function () {
+ head.removeChild(script);
+ };
+
+ head.appendChild(script);
+
+ } else {
+
+ method = method || 'GET';
- if (method === 'POST') {
- xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+ if (w.XMLHttpRequest) {
+ xhr = new XMLHttpRequest();
+ } else if (w.ActiveXObject) {
+ xhr = new ActiveXObject('Microsoft.XMLHTTP'); // IE < 9
}
- xhr.send(query);
+ if (xhr) {
+ method = method.toUpperCase();
- xhr.onreadystatechange = function () {
- if (xhr.readyState === 4 && xhr.status === 200) {
- if (callback) {
- try {
- callback(xhr.responseText);
- } catch (e) {}
+ if (method === 'GET') {
+ url += querystart + query;
+ query = null;
+ }
+
+ if (nocache) {
+ url += (method === 'POST') ? querystart + timestamp : '&' + timestamp;
+ }
+
+ // Douglas Crockford: "Synchronous programming is disrespectful and should not be employed in applications which are used by people"
+ xhr.open(method, url, true);
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (callback) {
+ try {
+ callback(xhr.responseText, xhr.status);
+ } catch (e) {}
+ }
}
+ };
+
+ if (method === 'POST') {
+ xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
- };
+
+ xhr.send(query);
+
+ }
}
}
};
}
- // Set Chibi's global namespace here
+ // Set Chibi's global namespace here ($)
w.$ = chibi;
}());
Please sign in to comment.
Something went wrong with that request. Please try again.