聽說你還不會用Ajax,現在它來了

Ajax

1.傳統請求和異步請求

  • 傳統請求: 基於超級鏈接 地址欄 form表單 地址欄 location.href 發起的請求全部是傳統請求
    • 特點: 請求之後,刷新整張頁面
    • 缺點: 由於刷新了整張頁面,用戶操作被中斷,造成大量網絡流量的極大浪費。
  • 異步請求: 基於ajax發起的請求都是異步請求
    • 特點: 多個請求並行發生,請求之間互不影響,請求之後頁面不動,刷新頁面的局部

2.什麼是Ajax

Ajax 即Asynchronous Javascript And XML(異步 JavaScript 和 XML)。他不是一種新的編程語言,而是一種通過異步實現網頁的局部更新技術。


3.Ajax的核心對象

XMLHttpRequest 對象是一個javascript對象,存在着瀏覽器差異。簡稱xhr對象


4.Ajax的編程思路

1. 創建xhr對象
var xhr ;
	if(window.XMLHttpRequest){ 
        xhr = new XMLHttpRequest();
    }else{
        xhr =  new ActiveXObject("Microsoft.XMLHTTP");
    }

2. 發送請求並傳遞參數
	xhr.open("GET|POST","url?參數"); xhr.send(null);

3. 處理響應並渲染頁面
	xhr.onreadystatechange = function(){ 
    if(xhr.readyState == 4 && xhr.status == 200){
            console.log(xhr.resonseText);
        }
	} 

5.發送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);
 	}
}

6.發送POST方式請求

//1. 創建xhr對象
var xhr; if(window.XMLHttpRequest){
xhr = new XMLHttpRequest(); }else{
xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
//2.發送請求,並傳遞參數
xhr.open("POST","/ajax_day2/test");
xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded"); xhr.send("name=zhangsan");
//3.處理響應
xhr.onreadystatechange = function(){
if(xhr.readyState==4 && xhr.status==200){ console.log(xhr.reponseText);
} }

7.Ajax的數據交換機制

JSON (JavaScript Object Notation, JS對象標記) 是一種輕量級的數據交換格式。

1. 如果服務端響應的不再是字符串而是對象或者是集合類型時,無法直接將對象響應給客戶端。 
		如: User、List<User>、Map<String,User> 需要將對象轉爲json格式字符串響應給ajax。
		
		
2.如何將對象轉爲json格式的字符串
  User user = new User("21","chenyn",23,123.0);
  String userJson = JSONObject.toJSONString(user); // fastjson json
	response.setContentType("application/json;charset=UTf-8");
  PrintWriter writer = response.getWriter();
  writer.out(userJson);

3.前端的ajax函數中應該如何處理json格式的字符串
	xhr.onreadystatechange = function(){ 
		if(xhr.readyState==4 && xhr.status==200){
			var json = xhr.responseText;// json
			var userObj = eval("("+xhr.responseText+")"); //轉爲js對象" 
			console.log(userObj.id);//
			console.log(userObj.name);
		} 
}

4.處理json字符串中的日期格式問題
    var userJson = JSONObject.toJsonStringWithDateFormat(user,"yyyy-MM-dd");

8.jQuery對Ajax的封裝

1.jQuery提供了一個全局函數
  $.ajax({
    type:"POST|GET",
    url:"",
    data:"name=張三|{key:value}",
    dataType:"JSON",
    success:function(result){
       console.log(result);
    }
  })
2.發送GET方式的異步請求 
    $.get(url,data,function(result){},"JSON");

3.發送POST方式的異步請求
    $.post(url,data,function(result){},"JSON");

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