思路
/ajax的get方式
1.type:"get"
2.url 寫在open函數(shù)里面船老,包含數(shù)據(jù)
3.回調(diào)函數(shù)亲配,將處理得到的數(shù)據(jù)function(data){操作},/*ajax的post方式 數(shù)據(jù)不能放在地址欄里面,所以要有data屬性缘眶,放在send函數(shù)里面發(fā)送
1.type:"post"
2.url
3.data{
diyigeshuju:
diergeshuju:
}
4,回調(diào)函數(shù)
*//ajax的跨域操作滑凉,JSONP淹遵。通過sccript標(biāo)簽發(fā)送api請求咽安,然后調(diào)用回調(diào)函數(shù)耕捞,得到數(shù)據(jù)
1.type:"JSONP
2.url
3cab:(地址欄里面的key )
4,回調(diào)函數(shù)/
代碼實現(xiàn)
$.ajax=function(options){
var transp=window.ActiveXObject?new ActiveXObject():new XMLHttpRequest();
switch(options.type){
case "get":{
transp.open("get",options.url,true);
transp.onreadystatechange=function(){
if(transp.readyState==4){
if(transp.status==200||transp.status==304){
var msg=transp.responseText;
options.success(msg);//回調(diào)函數(shù)
}
}
}
transp.send();
break;
}
case "post":{
transp.open("post",options.url,true);
transp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
transp.onreadystatechange=function(){
if(transp.readyState==4){
if(transp.status==200||transp.status==304){
var msg=transp.responseText;
options.success(msg);
}
}
}
var str="";
for(var arr in options.data){
str+=arr+"="+options.data[arr]+"&";
}
transp.send(str.substring(0,str,length-1));
break;
}
case "JSONP":{
var script=document.createElement("script");
var name="_cbk"+parseInt(Math.random()*1000)+new Date().getTime();
script.src=options.url+"&"+options.cab+"="+name;
window[name]=function(data){
options.success(data);
script.remove();
delete window[name];
}
document.body.appendChild(script);
break;
}
}
}