原生ajax與jquery-ajax

一、原生ajax

get方式:

//1. 創建xhr對象
var xhr ; 
if(window.XMLHttpRequest){
	xhr = new XMLHttpRequest(); 
}else{
	xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
}
//2.發送請求,並傳遞參數
xhr.open("GET", "/ajax_day2/test?name"=+zhangsan);
xhr.send();
//3.處理響應
xhr.onreadystatechange = function(){ 
  if(xhr.readyState==4 && xhr.status==200){
     console.log(xhr.responseText);//resonseText獲得字符串形式的響應數據(獲得字符串)
   //TODO填寫js/jquery代碼
 	}
}

案例:
在這裏插入圖片描述

post方法:

//1. 創建xhr對象
var xhr ; 
if(window.XMLHttpRequest){
	xhr = new XMLHttpRequest(); 
}else{
	xhr = new ActiveXObject("Microsoft.XMLHTTP"); 
}
//2.發送請求,並傳遞參數
xhr.open("POST", "url");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");//用來模擬form進行傳遞數據編碼 
xhr.send("參數");//請求體的傳參(沒有長度限制) xhr.send("name=zhansan&age=12")
//3.處理響應
xhr.onreadystatechange = function(){ 
  if(xhr.readyState==4 && xhr.status==200){
     console.log(xhr.responseText);//resonseText獲得字符串形式的響應數據(獲得字符串)
   //TODO填寫js/jquery代碼
 	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章