
本文共 4635 字,大约阅读时间需要 15 分钟。
1.传统请求和异步请求
传统请求:基于超级链接、地址栏、form表单、location.href 发起的请求全部是传统请求。
特点:请求之后,刷新整张页面。
缺点:由于刷新了整张页面,用户操作被中断,造成大量网络流量的浪费。
异步请求:基于ajax发起的请求都是异步请求。
特点:多个请求并行发生,请求之间互不影响,请求之后页面不动,刷新页面的局部
2.什么是Ajax
Ajax即 Asynchronous Javascript And XML(异步JavaScript和XML)。他不是一种新的编程语言,而是一种通过异步实现网页的局部刷新技术。
3.Ajax的核心对象
XML HttpRequest对象是一个javascript对象,存在着浏览器差异,简称xhr对象
1) IE(内核) new ActiveXObject("Microsoft.XMLHTTP")
2) Webkit(内核) new XMLHttpRequest()
4.Ajax的编程思路
1.创建xhr对象
var xhr;if(window.XMLHttpRequest){ //true Webkit内核 xhr = new XMLHttpRequest();}else{ //false IE内核 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依赖 jsonresponse.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的封装
前提是先引入对应JQuery的核心JS文件
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"); 发送请求、传递参数、处理响应并指定相应的数据类型 $.get(url); 发送get方式请求、不传递参数、不处理响应$.get(url,data); 发送get方式请求、传递参数、不处理响应$.get(url,function (result) {}); 发送get方式请求、不传递参数、处理响应或者:$.getJSON(url,function(result){ });
3.发送POST方式的异步请求
$.post(url,data,function(result){},"JSON");其他的与GET方式类似
9. 案例
$(function () { $("#loginButtonId").click(function () { var username = $("#form-username").val(); var password = $("#form-password").val(); var code = $("#form-code").val(); $.ajax({ type: "post", //dataType: "json", data: {username:username,password:password,code:code}, url: "${pageContext.request.contextPath}/admin/login", success:function (data) { if('登录成功' == data){ window.location.href = "${pageContext.request.contextPath}/index.jsp" }else{ //empty是将标签内的值清除,标签还在,remove标签就不在了 $("#msgDiv").empty(); $("#msgDiv").append(data); } }, error:function () { alert("出错了"); } }); }); });
注意:
1.当后台响应json格式数据时如果指定了响应类型为application/json时,jquery封装的ajax会自动转为js对象|数组。
2.如果在前台发送ajax请求时明确指定dataType属性为JSON时,即使后台不设置响应类型结果也会自动转为js对象|数组。
3.推荐前台设置响应类型,服务器端同样设置响应类型,结果一定为js对象|数组。
4.如果发送的请求没有响应结果void,或者响应结果不是JSON类型数据,是String或者其他类型数据,则前台一定不要指定 dateType为JSON,否则会报错,会进入error function()中,不会进入success function()中。
5.ajax可以发送同步请求:同步请求发送之后,在请求响应完毕之前浏览器处于锁定状态。
发表评论
最新留言
关于作者
