Ajax
AJAX,即 Asynchronous JavaScript and XML(非同步的 JavaScript 和 XML),是一種在無需重新載入整個網頁的情況下,能夠更新部分網頁的技術。
使用原生程式碼
document.getElementById("search").onclick=function(){
//新建XMLHttpRequest物件
var request = new XMLHttpRequest();
// 傳送請求:
request.open("GET","service.php?number="+document.getElementById("keyword").value);
request.send();
request.onreadystatechange = function(){// 狀態發生變化時,函式被回撥
if(request.readyState===4){// 成功完成
// 判斷響應結果:
if(request.status===200){
// 成功,通過responseText拿到響應的文字:
return success(request.responseText);
}else{
// 失敗,根據響應碼判斷失敗原因:
alert("發生錯誤:"+request.status);
}
}
}
}
document.getElementById("save").onclick=function(){
var request = new XMLHttpRequest();
request.open("POST","service.php");
var data = "name=" + document.getElementById("staffName").value
+ "&number=" + document.getElementById("staffNumber").value
+ "&sex=" + document.getElementById("staffSex").value
+ "&job=" + document.getElementById("staffJob").value;
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function(){
if(request.readyState===4){
if(request.status===200){
return success(request.responseText);
}else{
alert("發生錯誤:"+request.status);
}
}
}
}
複製程式碼
使用Json
document.getElementById("search").onclick=function(){
var request = new XMLHttpRequest();
request.open("GET","service2.php?number="+document.getElementById("keyword").value);
request.send();
request.onreadystatechange = function(){
if(request.readyState===4){
if(request.status===200){
var data = JSON.parse(request.responseText);
if(data.success){
return success(data.msg);
}else{
return success("出現錯誤:" + data.msg);
}
}else{
alert("發生錯誤:"+request.status);
}
}
}
}
document.getElementById("save").onclick=function(){
var request = new XMLHttpRequest();
request.open("POST","service2.php");
var data = "name=" + document.getElementById("staffName").value
+ "&number=" + document.getElementById("staffNumber").value
+ "&sex=" + document.getElementById("staffSex").value
+ "&job=" + document.getElementById("staffJob").value;
request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
request.send(data);
request.onreadystatechange = function(){
if(request.readyState===4){
if(request.status===200){
var data = JSON.parse(request.responseText);
if(data.success){
return success(data.msg);
}else{
return success("出現錯誤:" + data.msg);
}
}else{
alert("發生錯誤:"+request.status);
}
}
}
}
複製程式碼
使用Json+JQuery
$(document).ready(function(){
$("#search").click(function(){
$.ajax({
type: "GET",
url: "service2.php?number="+$("#keyword").val(),
dataType: "json",
success: function(data){
if(data.success){
$("#searchResult").html(data.msg);
}else{
$("#searchResult").html("出現錯誤:" + data.msg);
}
},
error: function(jqXHR){
alert("發生錯誤:"+jqXHR.status);
}
})
})
$("#search").click(function(){
$.ajax({
type: "POST",
url: "service2.php",
dataType: "json",
data: {
name: $("#staffName").val(),
number: $("#staffNumber").val(),
sex: $("#staffSex").val(),
job: $("#staffJob").val()
},
success: function(data){
if(data.success){
$("#createResult").html(data.msg);
}else{
$("#createResult").html("出現錯誤:" + data.msg);
}
},
error: function(jqXHR){
alert("發生錯誤:"+jqXHR.status);
}
})
})
})
複製程式碼
在現代瀏覽器上寫AJAX主要依靠XMLHttpRequest
物件,對於低版本的IE,需要換一個ActiveXObject
物件:
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject('Microsoft.XMLHTTP');
}
複製程式碼
跨域
使用HTML5規範定義的跨域策略:CORS(Cross-Origin Resource Sharing)
配置跨域過濾器
package Filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CorsFilter implements Filter {
public void destroy() {}
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
HttpServletResponse res = (HttpServletResponse) resp;
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,x-requested-with");
res.setCharacterEncoding("UTF-8");
res.setContentType("application/json");
chain.doFilter(req, res);
}
public void init(FilterConfig config) throws ServletException {}
}
複製程式碼
在web.xml中
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>Filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
複製程式碼
@CrossOrigin註解
Spring 4.2之後提供了跨域註解 @CrossOrigin,可以用在方法或Controller上;
在controller類上加上如下註解:
@CrossOrigin(allowCredentials = "true",allowedHeaders = "*") //實現跨域
複製程式碼
DEFAULT_ALLOW_CREDENTIALS = true: 需配合前端設定xhrFields授信後,使得跨域session共享,前端ajax請求新增設定:
xhrFields: {withCredentials:true}
DEFAULT_ALLOWED_HEADERS = *:允許跨域傳輸所有的header引數,將用於使用token放入header域做session共享的跨域請求
JQuery
jQuery 是一個高效、精簡併且功能豐富的 JavaScript 工具庫,它的所有功能都是通過JavaScript訪問的。它提供的 API 易於使用且相容眾多瀏覽器,這讓諸如 HTML 文件遍歷和操作、事件處理、動畫和 Ajax 操作更加簡單。jQuery API 中文文件
使用:通過 script 標籤引入 jQuery 庫。推薦BootCDN,裡面收錄了很多前端開源庫,介面簡潔乾淨美觀。
入手學習:慕課網Aaron艾倫老師的JQuery基礎課程
參考
慕課課程《Ajax全接觸》