同步和異步javascript
同步現象:客戶端發送請求到服務器端,當服務器返回響應以前,客戶端都處於等待 卡死狀態html
異步現象:客戶端發送請求到服務器端,不管服務器是否返回響應,客戶端均可以隨 意作其餘事情,不會被卡死java
Ajax的運行原理jquery
頁面發起請求,會將請求發送給瀏覽器內核中的Ajax引擎,Ajax引擎會提交請求到 服務器端,在這段時間裏,客戶端能夠任意進行任意操做,直到服務器端將數據返回 給Ajax引擎後,會觸發你設置的事件,從而執行自定義的js邏輯代碼完成某種頁面1 功能。web
js原生的Ajax技術,異步和同步操做ajax
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> /* 1)建立Ajax引擎對象 2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎) 3)綁定提交地址 4)發送請求 5)接受響應數據 */ function f1(){ //1)建立Ajax引擎對象 var xmlhttp=new XMLHttpRequest(); //2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎) xmlhttp.onreadystatechange=function(){ //5)接受響應數據 if(xmlhttp.readyState==4&&xmlhttp.status==200){ var res=xmlhttp.responseText; document.getElementById("span1").innerHTML=res; } } //3)綁定提交地址 xmlhttp.open("GET", "${pageContext.request.contextPath}/AjaxServlet", true);//請求方式,請求地址,是否異步 //4)發送請求 xmlhttp.send(); } function f2(){ //1)建立Ajax引擎對象 var xmlhttp=new XMLHttpRequest(); //2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎) xmlhttp.onreadystatechange=function(){ //5)接受響應數據 if(xmlhttp.readyState==4&&xmlhttp.status==200){ var res=xmlhttp.responseText; alert(res); } } //3)綁定提交地址 xmlhttp.open("POST", "${pageContext.request.contextPath}/AjaxServlet", true);//請求方式,請求地址,是否異步 xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); //4)發送請求 xmlhttp.send("name=張三"); } function f3(){ //1)建立Ajax引擎對象 var xmlhttp=new XMLHttpRequest(); //2)爲Ajax引擎對象綁定監聽(監聽服務器已將數據響應給引擎) xmlhttp.onreadystatechange=function(){ //5)接受響應數據 if(xmlhttp.readyState==4&&xmlhttp.status==200){ var res=xmlhttp.responseText; document.getElementById("span2").innerHTML=res; } } //3)綁定提交地址 xmlhttp.open("GET", "${pageContext.request.contextPath}/AjaxServlet", false);//請求方式,請求地址,是否異步 //4)發送請求 xmlhttp.send(); } </script> </head> <body> <input value="異步訪問" type="button" onclick="f1()"> <span id="span1"></span> <br> <input value="同步訪問" type="button" onclick="f3()"> <span id="span2"></span> <br> <input value="測試" type="button" onclick="alert()"> </body> </html>
Ajaxservlet:json
package com.oracle.web; import java.io.IOException; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /*request.setCharacterEncoding("utf-8"); String name=request.getParameter("name"); response.setContentType("text/html;charset=utf-8"); response.getWriter().write(name+"你好");*/ try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } response.getWriter().write(new Random().nextDouble()+""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Json數據格式數組
json是一種與語言無關的數據交換的格式,做用:瀏覽器
使用ajax進行先後臺數據交換服務器
移動端與服務端的數據交換
Json格式:
1)對象格式:{"key1":obj,"key2":obj,"key3":obj...}
2)數組/集合格式:[obj,obj,obj...]
例如:user對象 用json數據格式表示
{"username":"zhangsan","age":28,"password":"123","addr":"淄博"}
List<Product> 用json數據格式表示
[{"pid":"10","pname":"小米4C"},{},{}]
注意:對象格式和數組格式能夠互相嵌套
json的key是字符串 jaon的value是Object
json的解析:
json是js的原生內容,也就意味着js能夠直接取出json對象中的數據
將java的對象或集合轉成json形式字符串
json的轉換插件是經過java的一些工具,直接將java對象或集合轉換成json字符串。
經常使用的json轉換工具備以下幾種:
1)jsonlib
2)Gson:google
3)fastjson:阿里巴巴
json例子:
<script language="JavaScript"> /** * 案例一 * {key:value,key:value} * * class Person{ * String firstname = "張"; * String lastname = "三豐"; * Integer age = 100; * } * * Person p = new Person(); * System.out.println(p.firstname); */ var person={"firstname":"張","lastname":"三豐","age":100}; alert(person.lastname); alert(person.age); </script>
<script language="JavaScript"> /** * 案例二 * [{key:value,key:value},{key:value,key:value}] * */ var persons=[{"name":"zhangsan",age:18},{"name":"lisi",age:19},{"name":"wangwu",age:20}]; alert(persons[1].name); alert(persons[2].age); </script>
<script language="JavaScript"> /** * 案例三 * { * "param":[{key:value,key:value},{key:value,key:value}] * } * * */ var school= { "c0601班":[{"name":"張三","age":23},{"name":"李四","age":20}], "c0602班":[{"name":"趙四","age":34},{"name":"王強","age":25}] }; alert(school.c0601班[1].name); </script>
jQuery的Ajax技術
jquery是一個優秀的js框架,天然對js原生的ajax進行了封裝,封裝後的ajax的操 做方法更簡潔,功能更強大,與ajax操做相關的jquery方法有以下幾種,但開發中 常常使用的有三種
1)$.get(url, [data], [callback], [type])
2)$.post(url, [data], [callback], [type])
其中:
url:表明請求的服務器端地址
data:表明請求服務器端的數據(能夠是key=value形式也能夠是json格式)
callback:表示服務器端成功響應所觸發的函數(只有正常成功返回才執行)
type:表示服務器端返回的數據類型(jquery會根據指定的類型自動類型轉換)
經常使用的返回類型:text、json、html等
3)$.ajax( { option1:value1,option2:value2... } ); ---- 之後在掌握
經常使用的option有以下:
async:是否異步,默認是true表明異步
data:發送到服務器的參數,建議使用json格式
dataType:服務器端返回的數據類型,經常使用text和json
success:成功響應執行的函數,對應的類型是function類型
type:請求方式,POST/GET
url:請求服務器端地址
例子:
user實體類:
package com.oracle.domain; public class User { private String name ; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [name=" + name + ", age=" + age + "]"; } }
jsp頁面代碼
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script src="${pageContext.request.contextPath }/jquery-1.11.3.min.js" type="text/javascript"></script> <script type="text/javascript"> function f1(){ $.get( "${pageContext.request.contextPath }/Ajax2Servlet", {"name":"zhangsan","age":18}, function(data){ alert(data.name); }, "json" ) } function f2(){ $.post( "${pageContext.request.contextPath }/Ajax2Servlet", {"name":"zhangsan","age":18}, function(data){ alert(data.name); }, "json" ) } function f3(){ $.ajax({ url:"${pageContext.request.contextPath }/Ajax2Servlet", async:true, type:"POST", data:{"name":"lusi","age":18}, success:function(data){ alert(data.name); }, error:function(){ alert("請求失敗"); }, dataType:"json" }) } </script> </head> <body> <input type="button" value="get異步提交服務器" onclick="f1()"> <input type="button" value="PSOT同步提交服務器" onclick="f2()"> <input type="button" value="ajax提交服務器" onclick="f3()"> </body> </html>
servlet代碼:
package com.oracle.web; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.oracle.domain.User; public class Ajax2Servlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("name"); String agestr=request.getParameter("age"); int age=Integer.parseInt(agestr); User user=new User(); user.setAge(age); user.setName(name); Gson gs=new Gson(); String js=gs.toJson(user); System.out.println(js); response.getWriter().write("{\"name\":\""+name+"\",\"age\":"+age+"}"); response.getWriter().write(js); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }