Skip to content

Instantly share code, notes, and snippets.

@mtmzorro
Created April 21, 2014 05:26
Show Gist options
  • Save mtmzorro/11133088 to your computer and use it in GitHub Desktop.
Save mtmzorro/11133088 to your computer and use it in GitHub Desktop.
var myUtil = (function() {
var jsonpMethods = {},
head = document.getElementsByTagName('head')[0],
jsonpCount = 0;
var getJSON = function(url, params, callbackFuncName, callback) {
var paramsArr = [],
jsonp = 'jsonp_' + new Date().getTime() + '_' + (jsonpCount++);
for (var key in params) {
paramsArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(params[key]));
}
url += ((url.indexOf('?') !== -1) ? '&' : '?') + callbackFuncName + "=myUtil.jsonpMethods." + jsonp + "&" + paramsArr.join("&");
jsonpMethods[jsonp] = function(data) {
delete jsonpMethods[jsonp];
head.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.charset = "UTF-8";
script.src = url;
head.appendChild(script);
return true;
};
return {
jsonpMethods: jsonpMethods,
getJSON: getJSON
};
})();
myUtil.getJSON("xxx.php", {}, "jsoncallback", function(data){
console.log(data);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment