Ajax知识点
以下部分知识点是看了燕十八老师的的视频整理出来的,并非原创,在此说明。
1、实现ajax的方式(比较古老)。
- 利用<a href="xxx.php"></a>请求后台,并在后台返回header("HTTP/1.1 204 no content"); 利用http协议的204特性。
- document.createElement("img").setAttribute("src","xxx.php"); 创建一个img标签,设置src属性,浏览器将会请求src对应的资源。
- 利用css、script标签加载的特性,完成请求。(原理一样:代替浏览器发送请求)。
实例:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 </head> 7 <body> 8 <img alt="头像" src="img/touxiang.png"> 9 <p><a href="vote.do">第一种投票方式</a></p> 10 <p><input type="button" value="第二种投票方式" onclick="voteHandler();"/></p> 11 </body> 12 </html> 13 <script> 14 function voteHandler(){ 15 var oImg = document.createElement("img"); 16 oImg.src = "vote.do"; 17 } 18 </script>
1 package com.sgepit.ajax; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 @WebServlet("/vote.do") 12 public class VoteServlet extends HttpServlet{ 13 14 private int count = 0; 15 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 resp.setStatus(204); 19 resp.setHeader("HTTP/1.1", "no content"); 20 count++; 21 System.out.println("count="+count); 22 } 23 }
2、FORM+IFrame实现Aajx效果
实例:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>form+iframe实现ajax</title> 6 </head> 7 <body> 8 <p>说明:输入admin/123456表示成功,其余均失败</p> 9 <form action="ajax2.do" method="post" target="tempFrame"> 10 <p>username:<input type="text" id="username" name="username"/></p> 11 <p>password:<input type="password" id="password" name="password"/></p> 12 <p><input type="submit" value="submit"/></p> 13 </form> 14 <iframe id="tempFrame" name="tempFrame" style="display:none;"></iframe> 15 </body> 16 </html> 17 <script> 18 window.onload = function(){ 19 document.getElementById("tempFrame").onload = function(){ 20 var result = this.contentWindow.document.body.innerText; 21 alert("后台返回结果:" + result); 22 } 23 } 24 </script>
1 package com.sgepit.ajax; 2 3 import java.io.IOException; 4 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 @WebServlet("/ajax2.do") 12 public class Ajax2 extends HttpServlet { 13 14 @Override 15 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 16 String username = req.getParameter("username"); 17 String password = req.getParameter("password"); 18 resp.setCharacterEncoding("utf-8"); 19 if(username.equals("admin") && password.equals("123456"))resp.getWriter().print("登录成功"); 20 else resp.getWriter().print("登录失败"); 21 } 22 }
在不使用XMLHttpRequest对象的情况下,我们也可以使用js对服务器请求,同时带来页面不刷新的效果。
3、ajax实现文件无刷新上传的方式:
- form+iframe实现伪ajax效果。
- 利用flash来实现。swfupload插件
- html5可以实现。(读取本地文件,base64、ajax发送)
4、XMLHttpRequest详细探讨:
- 返回值类型
- responseText:服务响应的主体信息,body信息。
- responseXML:对于大量的格式化文档,可以用XML来传输或交换,由后台程序把数据封装在XML文档时,js接收XML对象并解析该内容。
- status:是服务器的返回状态码,例如:200代表成功,403 forbidden禁止,404 not found未找到,50X系列,内容服务器错误。
- statusText:服务器返回的状态码,对应的文字描述。
- readyState:XMLHttpRequest 对象自身的状态码,0-4。
- onreadystatechange:事件属性,绑定当XMLHttpRequest对象的状态发生变化的时候,激发函数。
- 详细用法
- open("请求方式",url,异步/同步); false表示同步,true表示异步。
- send(null/参数); 参数的写法:k1=v1&k2v2....
- setRequestHeader(key,value);设置请求的头信息。
- Abort() 忽略,不再进行下去了,到此为止。
- getResponseHeader;获取响应的某个头信息。
- getAllResponseHeaders; 获取响应的所有头信息。
特别说明:原生ajax在提交form表单(post提交)的数据的时候,在ajax.send(data)之前,需要先设置头信息。比如:ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
5、jsonp跨域
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>JSONP跨域</title> <style> #wrap { width: 800px; height: 400px; } #search { height: 50px; margin: 10px 10px 0px 10px; } #content { float: left; width: 600px; height: 48px; line-height: 50px; padding-left: 10px; border: 1px solid #8D8D8D; } #btn { float: left; width: 150px; height: 50px; line-height: 50px; background:#3385ff; color: #fff; text-align: center; cursor: pointer; } #list { margin:0; padding:0; width:600px; height: 300px; margin: 0 10px; display: none; list-style: none; padding-left:10px; border: 1px solid #ccc; } #list li{ font-weight: bold; height:25px; line-height: 25px; } #list li:hover{background: #ccc;} .clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden } .clearfix { *+height: 1%; } </style> </head> <body> <div id="wrap"> <div id="search" class="clearfix"> <div id="content" contenteditable="true"></div> <div id="btn">GOOGLE</div> </div> <ul id="list"> </ul> </div> </body> </html> <script> window.onload = function(){ var oBtn = document.getElementById("btn"); var oContent =document.getElementById("content"); oBtn.onclick = function(){ var value = oContent.innerText; var url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q="+value+"&callback=callback"; var eleScript = document.createElement("script"); eleScript.setAttribute("src",url); document.getElementsByTagName("head")[0].appendChild(eleScript); } } function callback(data){ var oList = document.getElementById("list"); var result = ""; if(null != data && null != data.responseData.results){ var array = data.responseData.results; var oFragment = document.createDocumentFragment(); for(var i =0, len = array.length;i<len;i++){ var title = array[i].title; var content = array[i].content; var oLi = document.createElement("li"); oLi.innerHTML = title + ":" + content; oFragment.appendChild(oLi); } oList.appendChild(oFragment); } } </script>
6、HTML5与Ajax上传显示进度条
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>H5文件上传,显示进度条</title> 6 <style> 7 #wrap{width:600px; height:400px; border:1px solid #ccc; margin:10px auto;} 8 9 </style> 10 </head> 11 <body> 12 <p>文件上传:<input type="file" id="file" onchange="uploadFile(this);"></p> 13 <p>上传进度:<progress id="progress" max="100" value="0"></progress></p> 14 <p></p> 15 <p></p> 16 </body> 17 </html> 18 <script> 19 function uploadFile(oFile){ 20 var formData = new FormData(); 21 formData.append("file",oFile.files[0]); 22 23 var xhr = new XMLHttpRequest(); 24 xhr.open("POST","ajax3.do",true); 25 var progress = document.getElementById("progress"); 26 xhr.upload.onprogress = function(ev){ 27 if(ev.lengthComputable)progress.value = parseInt(ev.loaded/ev.total*100);; 28 } 29 xhr.send(formData); 30 } 31 </script>
1 package com.sgepit.ajax; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 import java.util.UUID; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 import org.apache.commons.fileupload.FileItem; 15 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 16 import org.apache.commons.fileupload.servlet.ServletFileUpload; 17 18 19 /** 20 * @author tengri 21 *文件上传 22 */ 23 @SuppressWarnings("all") 24 @WebServlet("/ajax3.do") 25 public class Ajax3 extends HttpServlet { 26 27 @Override 28 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 29 DiskFileItemFactory factory = new DiskFileItemFactory(); 30 factory.setSizeThreshold(2014 * 1024); 31 factory.setRepository(new File("D:/uploadTemp")); 32 System.out.println("jinru"); 33 ServletFileUpload upload = new ServletFileUpload(factory); 34 resp.setCharacterEncoding("utf-8"); 35 try { 36 List<FileItem> items = upload.parseRequest(req); 37 for(FileItem item : items){ 38 if(!item.isFormField()){ 39 //文件名 40 String fileName = item.getName(); 41 System.out.println(fileName); 42 //检查文件格式 43 String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase(); 44 //真实上传路径 45 StringBuffer sbRealPath = new StringBuffer(); 46 sbRealPath.append("D:/uploadFile/").append(UUID.randomUUID()).append(".").append(fileEnd); 47 File file = new File(sbRealPath.toString()); 48 item.write(file); 49 } 50 } 51 } catch (Exception e) { 52 53 } 54 super.doPost(req, resp); 55 } 56 57 }