1,局部刷新 、 異步記載
Ajax全程 Asynchronous And XML
2,Ajax 4個步驟
a,創建對象(兼容問題)
var xhr =null;
if(window.XMLHttpRequest){? ? xhr = new XMLHttpRequest();? }
else{? xhr = new ActiveXObject("Microsoft.XMLHTTP");?//IE6 }?
b,準備發送
//由于是get方法,url需要帶上參數
xhr.open("get","check.php?userName=?",false);
第一個參數:請求方式(對應后太街口的訪問方式)
第二個參數:URL
第三個參數:同步還是異步,false同步,true異步(默認) ,如果是false需要將回調函數刪除
c,執行發送
xhr.send(null);
參數:get請求: null? ?/? ?post請求:發送時參數請求
var param = " username="+username;
//設置xhr 請求頭信息,這個步驟只有post請求才有
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(param);
d,回調函數
xhr.onreadystatechange=function(){
? if(xhr.readyState == 4){
? ? ? ?if(xhr.status==200){
????????????var result = xhr.resphonseText;
? ? ? ? ? ? xhr.responseXML;
? ? ? ? ? ? JSON.parse(result);
? }
}
3,同步和異步原理
異步原理是單線程加事件隊列實現的。???
4,封裝
function myAjax(type,url,params,datatype,callback){
????????var xhr = null;
????????if(window.XMLHttpRequest){
? ????????????xhr = new XMLHttpRequest();
? ? ? ? }else{
????????????? xhr = new ActiveXObject("Microsoft.XMLHTTP");
????????}
????????if(type=="get"){
? ? ? ? ? ? if(params&¶ms!=null){
? ? ? ????????? ?url+="?"+params;
????????}? ? ? ? }
????????xhr.open(type,url,true);
????????if(type=="get"){
????????????????? ?xhr.send(null);
? ? ? ? ?}else{
????????????????xhr.setRequestHeader("content-type,"application/x-www-form-urlencoded");????????
????????????????xhr.send(params);
????????}
????????xhr.onreadystatechange=function(){
????????????if(xhr.readuState==4){
????????????????? if(xhr.status==200){
????????????????????????? var result = null;????
? ? ? ? ? ? ? ? ? ? ? ? ? if(datatype == "json"){
????????????????????????????????result = xhr.reponseText;
????????????????????????????????result = JSON.parse(result);
? ? ? ? ? ? ? ? ? ? ? ? ? }else if(datatype=="xml"){
????????????????????????????????result = xhr.reponseXML;
? ? ? ? ? ? ? ? ? ? ? ? ? }else{
????????????????????????????????result = xhr.reponseText;
? ? ? ? ? ? ? ? ? ? ? ? ? ?}????
? ? ? ? ? ? ? ? ? ? ? ? if(callback){? ?callback(result); }
? ? ? ? ? ? ? ? ?}
????????}? ????}????????}
5,同源策略
使用ajax的頁面和ajax的URL需要同源才能正常訪問,非同源訪問不到
同源:協議相同 、 域名相同、端口相同
6,跨域
本質:服務器返回了一個方法調用,這個方法是我們事先定義好的,而方法中的參數就是我們想要的數據.
動態創建script標簽
動態指定回調函數
同在script標簽中定義方法效果一致:
封裝: