如何使用原生JS实现类似jQuery的getJSON功能
2016-08-07 · 百度知道合伙人官方认证企业
育知同创教育
1【专注:Python+人工智能|Java大数据|HTML5培训】 2【免费提供名师直播课堂、公开课及视频教程】 3【地址:北京市昌平区三旗百汇物美大卖场2层,微信公众号:yuzhitc】
向TA提问
关注
展开全部
var $ = {
getJSON: function(url, params, callbackFuncName, callback){
var paramsUrl ="",
jsonp = this.getQueryString(url)[callbackFuncName];
for(var key in params){
paramsUrl+="&"+key+"="+encodeURIComponent(params[key]);
}
url+=paramsUrl;
window[jsonp] = function(data) {
window[jsonp] = undefined;
try {
delete window[jsonp];
} catch(e) {}
if (head) {
head.removeChild(script);
}
callback(data);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.charset = "UTF-8";
script.src = url;
head.appendChild(script);
return true;
},
getQueryString: function(url) {
var result = {}, queryString = (url && url.indexOf("?")!=-1 && url.split("?")[1]) || location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
};
getJSON: function(url, params, callbackFuncName, callback){
var paramsUrl ="",
jsonp = this.getQueryString(url)[callbackFuncName];
for(var key in params){
paramsUrl+="&"+key+"="+encodeURIComponent(params[key]);
}
url+=paramsUrl;
window[jsonp] = function(data) {
window[jsonp] = undefined;
try {
delete window[jsonp];
} catch(e) {}
if (head) {
head.removeChild(script);
}
callback(data);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.charset = "UTF-8";
script.src = url;
head.appendChild(script);
return true;
},
getQueryString: function(url) {
var result = {}, queryString = (url && url.indexOf("?")!=-1 && url.split("?")[1]) || location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
};
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询