JSONP:就是利用浏览器对html标签(如:a,img,link,script等)没有做跨域请求限制的情况,使用script加载跨域接口的url。
注:当本机请求服务器上数据的时候:会发生跨域;
地址类型:https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=&cb=liyang
function ajax(options){
var {type,url,success,error,data} = options;//解构模式接收传入的值
type = type || "get";//判断type请求类型,默认为get
data = data || {};//判断data数据是否为空,为空时设为空对象
var str = "";//用于地址的拼接
for(var i in data){//遍历data数据,并按照http地址形式进行拼接
str +=`${i}=${data[i]}&`;
}
if(type == "get" || type =="jsonp"){
var d = new Date();
url = url + "?" + str + "_init_" + d.getTime();//拼接完整地址,添加d.getTime()设置毫秒数,解决浏览器缓存问题
}
if(type == "jsonp"){//jsonp用于解决ajax不能跨域的问题
var script = document.createElement("script");
script.src = url;
document.body.appendChild(script);
window[data[data.column]] == function(res){
success && success(res);//成功时返回success(res),并将错误设为空
error = null;
};
setTimeout(function(res){
error && error(res);//同success
success = null;
},2000);
}else if(type == "get" || type == "post"){//当type类型为get或post时,构建ajax
var xhr = new XMLHttpRequest();//1
xhr.open(type,url,true);//2
if(xhr.onreadystatechange == 4 && xhr.status == 200){//3.ajax成功 success && success(xhr.responseText); }else if(xhr.onreadystatechange == 4 && xhr.status != 200){//ajax失败 error && error(xhr.status); } //get和Post的ajax发送方法判断 if(type == "get"){ xhr.send(); }else if(type == "post"){ xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//type为post时在发送前添加 xhr.send(str); }}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。