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");


版权声明:本文为qq_44534541原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_44534541/article/details/106757669