如何創建AJAX

首先在創建AJAX之前,需要注意如下幾個點:
(1)XMLHttpRequest 對象的工作流程
(2)兼容性處理
(3)事件的觸發條件
(4)事件的觸發順序

下面開始創建AJAX

 if(opt.url){
 // 第一步,XMLHttpRequest對象的聲明,以及瀏覽器的兼容
  var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP');
  var data = opt.data,
      url = opt.url,
      type = opt.type.toUpperCase(),
      dataArr= [];
   for(var k in data ){
	dataArr.push(k + '=' + data[k]);
	}
	if(type === 'GET'){
	  url = url + '?' + dataArr.join('&');
	  // 第二步,確定XMLHttpRequest的發送方式
	  xhr.open(type,url.replace(/\?$/g,''),true);
	  // 第三步,發送出去
	  xhr.send();
	}
	if(type === 'POST'){
	  xhr.open(type,url,true);
	  xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
	  xhr.send(dataArr.join('&'));
	}
	//第四步 響應,這裏這監聽事件,監聽成功或失敗的
	xhr.onload = function () {
	  if(xhr.status === 200 || xhr.status === 304){
	  	var res;
	  	if(opt.success && opt.success instanceof Function){
	  	 res = xhr.responseText;
	  	 if(typeof res === 'String'){
	  	    res = JSON.parse(res);
	  	    opt.success.call(xhr,res);
	  	 }
	  	}
	  } else {
	    if(opt.error && opt.error instanceof Function){
	    	opt.error.call(xhr,res);
	    }
	  }
	}
  
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章