标签:post set llb ajax insert other first top pos
基于原生JS的jsonp方法的实现
jsonp,相信大家并不陌生,是在js异步请求中解决跨域的方法之一,原理很简单,有不清楚的同学可以google下,这里就补详细解释了。在Jquery库中,jQuery直接封装有jsonp的方法,很简便,只需在ajax请求的参数中加入datatype:jsonp,jsonp:jsonpcallback即可,这里写下用原生js实现jsonp的源码。
load= function (url, cfg, success) { var op = Object.prototype.toString; var head = doc.getElementsByTagName(‘head‘)[0] || doc.head || doc.documentElement; if (op.call(cfg) === ‘[object Function]‘) { success = cfg; cfg = {}; } var type = cfg.type || ‘script‘, jsonpCallback = cfg.jsonpCallback || ‘fn‘; jsonp = type == ‘jsonp‘ ? (cfg.callbackName || ‘callback‘) : ‘‘, data = cfg.data || ‘‘, dataToParam = function (data) { var ret = [], key, e = encodeURIComponent; for (key in data) { ret.push(key + ‘=‘ + e(data[key])) } return ret.join(‘&‘); }, url = url + (/\?/.test(url) ? ‘&‘ : (jsonp || data) ? ‘?‘ : ‘‘) + (jsonp ? (jsonp + ‘=‘ + jsonpCallback) : ‘‘) + (data ? ‘&‘ + dataToParam(data) : ‘‘); loadScript = function (url, callback) { var script = doc.createElement("script"); script.type = "text/javascript"; script.charset = "utf-8"; if (script.readyState) { //IE script.onreadystatechange = function () { if (/loaded|complete/i.test(script.readyState)) { script.onreadystatechange = null; callback && callback.call(this); } }; } else { //Others script.onload = function () { callback && callback.call(this); }; } script.src = url; head.insertBefore(script, head.firstChild); }, removeScript = function () { var arg = arguments, script = arg[0], jsonpCallback = arg[1], type = Object.prototype.toString; //移除脚本 if (script && /script/i.test(script.tagName)) { script.parentNode.removeChild(script); } //移除回调 if (jsonpCallback && type.call(jsonpCallback) === ‘[object String]‘) { window[jsonpCallback] = null; } success(); }; var callback = window[jsonpCallback] = success; loadScript(url, function () { removeScript(this, jsonpCallback); }); }
调用方法:load(url,{"type":"script":"data":{}},calback);,原理和方法都很简单,但是jsonp方法只适合于GET方法儿不适合POST方法,这个还是需要注意的。
收藏了
http://lidongbest5.com/blog/20/
标签:post set llb ajax insert other first top pos
原文地址:http://www.cnblogs.com/18JG23/p/6797154.html