Ajax:Asynchronous JavaScript and XML 異步的JavaScript和XML技術
Ajax應用:側重與局部刷新/局部交互javascript
XMLHttpRequest對象(內置在瀏覽器中,js對象)
-------------------------------------------------------------------------------------------------------------------------
Ajax原理:Ajax是多種技術的綜合應用.
1.以XMLHttpRequest對象爲核心,實現請求的發送和響應結果的接受.
2.以JavaScript語言爲基礎,實現用戶操做和響應結果的解析,呈現到頁面.
3.以XML和JSON技術做爲數據傳輸格式.
4.以HTML,CSS等技術作界面及渲染.html
----------------------------------------------------------------------------------------------------------------------
Ajax基本使用(編程步驟)
java
一.發送Aajx請求
1.建立XMLHttpRequest對象 : new XMLHttpRequest();jquery
2.open方法:建立請求 open(get或post,url,同步異步);
- true:表示異步;false:表示同步;省略時默認異步web
3.send方法:發送請求 send(參數);
- get請求寫null;
- post請求寫參數值"key=value&key=value"ajax
二.服務器端處理
1.編寫Servlet或SpringMVC流程處理
2.返回text字符串或JSON格式的數據spring
三.Ajax回調處理
1.onreadystatechange事件: 當readyState屬性發生改變時觸發
2.readyState屬性:屬性值0-4,表示Ajax請求處理的過程。4表示請求處理完畢。
3.responseXML屬性:獲取服務器返回的XML信息
4.status屬性:獲取服務器響應的HTTP CODE,例如200,404,500等編程
例:1、三
function createXhr(){
var xhr = null;//存儲XMLHttpRequest對象
if(window.XMLHttpRequest){//非IE瀏覽器支持
xhr = new XMLHttpRequest();
}else{//IE
xhr = new ActiveObject("Microsoft.XMLHTTP");
}
return xhr;
}json
function sendRequest1(){
//利用XMLHttpRequest對象發送請求
var xhr = createXhr();
//建立一個hello.do請求
//open("get",請求url,同步異步(true爲異步))
xhr.open("get","hello.do",true);
//註冊回調處理函數
//readyState屬性:屬性值0-4:表示Ajax請求處理的過程
//4表示請求出完畢,200表示成功!
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
//獲取服務器返回的結果
var data = xhr.responseText;
var s1 = document.getElementById("s1");
s1.innerText = data;
}
}
//發送Ajax請求,get請求參數爲null,post請求參數是提交的數據
xhr.send(null);
}瀏覽器
二.
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter pw = response.getWriter();
System.out.println(1);
pw.print("Hello Ajax!");
pw.close();
}
}
web.xml中配置:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello.do</url-pattern>
</servlet-mapping>
<servlet>
------------------------------------------------------------------------------------------------------------------------
如何發送post請求:
xhr.open(「post」,」check.do」,true);
xhr.setRequestHeader(「content-type」,「application/x-www-form-urlencoded」);
xhr.send(「name=」+name);
例:
function sendRequest2(){
//獲取用戶名
var name = document.getElementById("name").value;
//發送Ajax請求
var xhr = createXhr();
xhr.open("post","check.do",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState==4&&xhr.status==200){
var data = xhr.responseText;
document.getElementById("s2").innerText = data;
}
}
xhr.send("name="+name);
document.getElementById("s2").innerHTML = "正在檢測中..."
}
-------------------------------------------------------------------------------------------------------------------------
JSON:JavaScript Object Notation
JavaScript對象格式,屬於js一種數據類型。
JSON類型格式以下:
var obj = {「key1」:value1,」key2」:value2};
obj.key1;//獲取value1值
obj.key2;//獲取value2值
例:
//標準的JSON對象
//var obj1 = {"name":"rose","age":20};
//alert(obj1.name);
//alert(obj1.age);
//var obj2 = {"name":"rose","age":20,"friends":["小曲","小樊","小邱","小關","andy"]};
//alert(obj2.friends[3]);
//var obj3 = {"name":"rose","age":20,"address":{"street":"北京中關村","zipcode":"1008611"}};
//alert(obj3.address.street);
//var obj4 = [{"id":1,"name":"北京"},{"id":2,"name":"上海"}]
//alert(obj4[1].name);
-----------------------------------------------------------------------------------------------------------------------
JSON對象的轉換
一.js將JSON字符串轉成JSON對象
-方法一:eval(「(「+json字符串+」)」);
-方法二:JSON.parse(json字符串);
-方法三:使用第三方js庫(略)
例:
var obj5 = '{"id":1,"name":"北京"}';
//將此字符串轉換成json對象的方法
//方法1:使用eval();
var obj6 = eval("("+obj5+")");
alert(obj6.id);
//方法2:使用JSON.parse()函數
var obj7 = JSON.parse(obj5);
alert(obj7.name);
//方法3:使用第三方js庫,例如json.js或jQuery.js
二.Servlet服務器端將Java實體對象轉成JSON字符串
-JSONObject:將單個對象轉成JSON字符串
-JSONArray:將集合轉成JSON字符串
例:
List<City> cities = getCities();
//將數據轉成JSON字符串
JSONArray jsonObj = JSONArray.fromObject(cities);
----------------------------------------------------------------------------------------------------------------------
jQuery對Ajax的支持
-*$.ajax():jQuery中發送請求最基本函數
格式:
$.ajax({
url:地址,
type:請求類型,
data:請求參數,
async:同步|異步,
dataType:返回結果類型,
success:成功回調函數,
error:失敗回調函數
});
-----------------------------------------------------------------------------------------------------------------------
Ajax與SpringMVC的整合
1.web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
2.Spring容器:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
<!-- 配置註解掃描,定義HandlerMapping,支持@RequestMapping -->
<mvc:annotation-driven/>
<!-- 配置組件掃描,掃描Controller,支持@Controller ,@Service等... -->
<context:component-scan base-package="com.tedu"/>
</beans>
3.controller:
package com.tedu.controller;
@Controller//掃描
public class LoadCityController {
@RequestMapping("/loadcities.do")
@ResponseBody//將方法返回的對象轉換成JSON字符串對象輸出
public List<City> execute(){
List<City> cities = new ArrayList<City>();
City c1 = new City(1,"合肥");
City c2 = new City(2,"亳州");
City c3 = new City(3,"利辛");
cities.add(c1);
cities.add(c2);
cities.add(c3);
return cities;
}
}
4.demo.html: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Ajax+SpringMVC+JSON</title> <script type="text/javascript" src="js/jquery-1.11.1.js"></script> <script type="text/javascript"> $(function(){ $.ajax({ url:"loadcities.do", type:"get", dataType:"json", success:function(data){ for(var i=0;i<data.length;i++){ var id = data[i].id; var name = data[i].name; var li = "<li>"+id+" "+name+"</li>"; $("#cities").append(li); } }, error:function(){ alert("加載失敗!"); } }); }); </script> </head> <body> <ul id="cities"> </ul> <ul id="stocks"> </ul> </body> </html>