query雖然屬于比較老的技術,但是相較于原生的JS寫起來還是反方便很多,現在流行使用VUE等開源的框架,但是這并非不妨礙咱們進行Jquery的學習,前端程序員成長的過程中Jquery是必須了解的類庫之一,后端程序員喜歡簡單粗暴,因而Jquery更受他們的歡迎.今天主要聊聊Jquery寫Ajax進行異步刷新.上一篇JQ入門傳送.
一、jQuery使用Ajax
想要了解jQuery如何使用Ajax,并且體會到它所帶來的方便性,那么就得了解原始的Ajax是如何編寫的,是怎樣的繁瑣,然后和Jquery的代碼進行對比,才會有所悟。
1.1、什么是Ajax?(順帶提一下)
全名:Asynchronous Javascript And Xml[異步javascript和xml],
同步和異步原理圖
同步就是瀏覽器發送一個請求到服務器端,網址會改變,頁面會被重新加載到新的頁面。如圖
異步就是瀏覽器發送一個請求到服務器端,網址不會改變,并且頁面只是局部刷新數據,能夠接收服務器返回的數據,如果需要完成這樣一個異步的過程,就需要使用Ajax技術,依靠Ajax引擎(XMLHttpRequest),原理如圖
Ajax是什么現在就應該知道了,看上面講解異步的原理就懂了,總結一句話,Ajax使用異步的方式從瀏覽器端發送請求,請求服務器端資源,并獲得內容的一種技術。
1.2、原始Ajax的用法。
如果編寫原始Ajax,那么就要總的分為4步,如下圖
第一步:獲取Ajax引擎
第二步:通過Ajax引擎執行回調函數,用來接收服務器端返回回來的數據。
第三步:Ajax引擎創建與服務器端的連接
第四步:發送請求到服務器,并且順帶將數據傳輸過去
總結:注意第三步和第四步中post請求和get請求的區別,如果是post請求,則需要加第三步中的65行代碼,并且所傳輸到服務器端的請求參數必須放在第四步的73行代碼中。如果是get請求的話,請求參數就直接放在第三步的62行代碼中(參考第三步的56行解釋),并且第三步中的65行代碼就不需要了,還有第四步中的73行代碼就不需要帶請求參數過去,參考70.71的注釋。
粘帖一份Ajax發送請求,并接收服務器端的數據的代碼,供參考。謝謝
<script type="text/javascript"> function sendData(obj){ //alert("失去焦點"); //1 當失去焦點時,獲得用戶輸入的內容 ,obj 等效 document.getElementById("xxx") var inputVal=obj.value; /* 2.1 創建核心類 */ var xmlhttp=null; if (window.XMLHttpRequest){// code for all new browsers xmlhttp=new XMLHttpRequest(); } else if (window.ActiveXObject) {// code for IE5 and IE6 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // 2.2 設置回調 xmlhttp.onreadystatechange=function(){ if(xmlhttp.readyState==4 && xmlhttp.status==200){ // 3.1 接收服務器響應的數據 ,獲得json數據,注意json也是文本 var data=xmlhttp.responseText; // 3.2 將字符串 轉換 json 對象 // 如果字符串 轉換 json 對象時不成功,使用格式:eval("('abc')"); var jsonData=eval("("+data+")"); // 3.3 判斷 --控制按鈕是否可用 var buttonObj=document.getElementById("buttonId"); var spanObj=document.getElementById("spanId"); if(jsonData.flag){ //可用 buttonObj.removeAttribute("disabled"); spanObj.style.color="#3D882D"; } else { //占用 buttonObj.setAttribute("disabled","disabled"); spanObj.style.color="#CC0000"; } // 3.4 到指定的位置顯示 spanObj.innerHTML=jsonData.msg; } }; // 2.3 連接 xmlhttp.open("POST","/day21/Demo04Servlet"); // * 設置編碼 xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded"); // 2.4 發送 xmlhttp.send("username=" + inputVal); } </script> </head> <body> <%-- <form action="" enctype="application/x-www-form-urlencoded"></form> --%> 用戶名:<input type="text" name="username" onblur="sendData(this)" /> <span id="spanId"></span> <br/> 密碼:<input type="password" name="password" /> <br/> <input id="buttonId" type="button" value="點我" />
1.3、jQuery使用Ajax
1.3.1、Ajax請求
第一層,最原始層,$.ajax ,一般不使用,完成更強大功能時需要使用。例如:如果出錯了,給出提示
第二層,load、$.get 、$.post 開發中常使用用于處理ajax
第三層,$.getJSON $.getScript 優化輔助
一行代碼搞定。但是jQuery使用Ajax有很多種用法,現在一一來介紹。
1、load的用法
必須在jQuery對象上觸發函數,發送ajax請求
格式:load(url, [data], [callback])
url:請求路徑
data:請求參數。參數格式為JSON
如果有參數,將是POST請求
如果沒有參數,將是GET請求
callback:成功之后回調,具有三個參數
第一個參數:返回值(一般為json,看返回的是什么)
第二個參數:狀態,其值可能是succuss,error,notmodify,timeout
第三個參數:ajax引擎XMLHttpRequest
實例:
OneServlet:服務器端響應
客戶端發送ajax請求
$(function(){ $("input").click(function(){ var url="/jQuery_test/OneServlet";//請求服務器端地址 /* load(url, [data], [callback]) 有data,所以是post請求 callback中有一個參數,那么就是其返回值對象,返回值類型是什么, 取決于服務器返回的是什么,如果是json數據,那么需要通過21行 代碼進行轉換。 */ var data={"username":"jack"}; $(this).load(url,data,function(data){ //需要手動轉成json對象 var jsonData=eval("("+data+")"); alert("成功" + jsonData.info); }); }); });
2、$.get方式
發送的就是get請求
格式:jQuery.get(url, [data], [callback], [type])
前三個參數和load方式一樣
type:返回內容格式,xml, html, script, json, text, _default(默認為json格式)
實例:
服務器端
客戶端
$( function(){ $("input").click(function(){ var url="/jQuery_test/OneServlet";//請求服務器端地址 /* jQuery.get(url, [data], [callback], [type]) */ var params={"username":"jack"}; //2 $.get 獲得數據為json對象 // * 當發送數據位字符串時,通過第四個參數設置類型 // * 服務器端可以通過 MIME類型 確定發送JSON數據 $.get(url,params,function(data){ alert(data.success); },"json"); }); });
3、$.post方式
跟$.get完全類似。
發送post請求
格式:jQuery.post(url, [data], [callback], [type])
不做解釋。一樣的。
4、$.ajax方式
底層原始ajax請求方式,出錯了,給出提示
常用格式:jQuery.ajax(settings); 使用json格式設置多項數據
看實例就懂了。
服務器端:雷同,不寫了。
客戶端
//4 $.ajax // * async 設置是否異步,true:表示異步(ajax) // * type 設置請求方式。例如:get、post // * url 設置請求路徑 // * data 請求參數 // * dataType 設置數據轉換類型,例如:xml, html, script, json // * success 成功回調 // * error 錯誤回調 $.ajax({ "async":true, "type":"POST", "url":url, "data":params, "success":function(data){ alert(data); }, "error" : function(){ alert("錯誤"); } });
1.3.2、表單序列化
serialize() 將表單中所有內容轉成字符串
所有內容:有name,有值(非空)--文本有數據,單選多選選中,下拉列表選中等
字符串:key=value&key=value&....
應用場景:$.get,當get請求時,將所有表單元素的內容都發送到服務器端時,不用一個一個拼接,直接使用該函數就搞定了。
serializeArray()將表單中所有內容轉成json數組
serialize()例子
核心代碼。
表單代碼如下
<h3>表單</h3> <form action=""> <table border="1" > <tr id="tr1"> <td class=""><label>姓名</label></td> <td><input type="text" name="username" class="textClass" value="jack" /></td> </tr> <tr> <td class=""><span>密碼</span></td> <td><input type="password" name="password" value="1234" /></td> </tr> <tr> <td>性別</td> <td> <input type="radio" name="gender" value="男" />男 <input type="radio" name="gender" value="女" checked="checked" />女 </td> </tr> <tr id="tr4"> <td>愛好</td> <td> <input type="checkbox" name="hobby" value="1"/>抽煙 <input type="checkbox" name="hobby" value="2" checked="checked"/>喝酒 <input type="checkbox" name="hobby" value="3" checked="checked"/>燙頭 </td> </tr> <tr> <td>我的照片</td> <td><input type="file" name="image" /></td> </tr> <tr> <td>學歷</td> <td> <select name="edu"> <option value="1">小班</option> <option value="2" selected="selected">中班</option> <option value="3">大班</option> <option value="4">學前班</option> </select> </td> </tr> <tr> <td></td> <td> <button type="button" id="buttonId">普通按鈕</button> <input type="submit" value="提交按鈕" /> <input type="reset" value="重置按鈕" /> <input type="image" value="圖片按鈕" src="" style="height: 30px;width: 50px" /> </td> </tr> </table> </form> <h3>公告信息</h3> <div> 未滿18慎進 </div>
結果如圖
看打印的結果,用&拼接而成,就是在get請求參數時放在url后面的格式,所以該應用場景是在$.get時。
serializeArray()實例。
結果
二、總結
復習了一下什么是Ajax,原始的Ajax的編寫(4步),然后使用jQuery對象來編寫ajax(一行代碼搞定);使用jQuery的話,要注意服務器端返回json數據時,json數據格式要正確。拒絕錯誤的編寫格式。比如"{'xx':'yy'}"或者"{'xx':xx}"這兩種都是錯誤的格式,
但是在返回的是字符串時,可以使用"{'XX':XX"}",然后在頁面使用eval進行轉換即可。
下一節會講解一下javascript的跨域數據傳輸問題(原始方法實現和使用jQuery實現)
本文轉載于博客園續杯涼茶的博客
Web數據交互方式,Ajax:
Ajax,Asynchronous Javascript And XML(異步JavaScript和XML),2005年被Jesse James Garrett提出的新術語,用來描述一種使用現有技術集合的新方法,包括:HTML或XHTML,CSS,JavaScript,DOM,XML,XSLT,以及最重要的XMLHttpRequest。 使用Ajax技術網頁應用能夠快速地將增量更新呈現在用戶界面上,而不需要重載(刷新)整個頁面,這使得程序能夠更快地回應用戶的操作。
jQuery
jQuery是一個快速、簡潔的JavaScript框架,是繼Prototype之后又一個優秀的JavaScript代碼庫(框架)于2006年1月由John Resig發布。封裝了JavaScript常用的功能代碼,提供一種簡便的JavaScript設計模式,優化HTML文檔操作、事件處理、動畫設計和Ajax交互。
Axios
一個基于promise的HTTP庫,可以用在瀏覽器和node.js中。
跨域資源共享(CORS)
CORS是一個W3C標準,全稱是"跨域資源共享"(Cross-origin resource sharing)。允許瀏覽器向跨源服務器,發出XMLHttpRequest請求,從而克服了AJAX只能同源使用的限制。
原生的Ajax同步&異步代碼案例
//Ajax Get 同步請求
function AjaxSynGet(url) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// xmlHttp.setRequestHeader("headName", "headName");
xmlHttp.open("GET", url + '&rnd=' + Math.random(), false);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.send(null);
var text=xmlHttp.responseText;
return text;
}
//Ajax Post 同步請求
function AjaxSynPost(url, param) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open("POST", url + '&rnd=' + Math.random(), false);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.setRequestHeader("headName", 'headValue');
xmlHttp.send(param);
var text=xmlHttp.responseText;
return text;
}
//Ajax Get 異步請求
// rtnFun: 函數
function AjaxGet(url, rtnFun) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
//IE
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp !=null) {
//get
xmlHttp.open("GET", url + '&rnd=' + Math.random(), true);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.send(null);
xmlHttp.onreadystatechange=function() {
//4="loaded"
if (xmlHttp.readyState==4) {
//200=OK
if (xmlHttp.status==200) {
var text=xmlHttp.responseText;
rtnFun(text);
}
}
}
}
}
//Ajax Post 異步請求
// rtnFun: 函數
function AjaxPost(url, param, rtnFun) {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp=new XMLHttpRequest();
//IE
} else if (window.ActiveXObject) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlHttp !=null) {
xmlHttp.open("POST", url + '&rnd=' + Math.random(), true);
xmlHttp.setRequestHeader("token","header-token-value");
xmlHttp.setRequestHeader("headName", 'headValue');
xmlHttp.send(param);
xmlHttp.onreadystatechange=function() {
//4="loaded"
if (xmlHttp.readyState==4) {
//200=OK
if (xmlHttp.status==200) {
var text=xmlHttp.responseText;
rtnFun(text);
}
}
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>原生的Ajax同步&異步代碼案例</title>
<!--r為參數防止瀏覽器緩存 -->
<script type="text/javascript" src="ajax.js?r=2"></script>
</head>
<body>
<div>
<span id="result1"></span>
<hr/>
<span id="result2"></span>
<hr/>
<span id="result3"></span>
<hr/>
<span id="result4"></span>
</div>
<script type="text/javascript">
// 1、Ajax Get同步請求
let result1=AjaxSynGet("http://192.168.1.116:8080/data/get?a=1");
console.log("result1",result1);
document.getElementById("result1").innerText=result1;
// 2、Ajax Post 同步請求
let result2=AjaxSynPost("http://192.168.1.116:8080/data/post?a=1","key=value");
console.log("result2",result2);
document.getElementById("result2").innerText=result2;
// 3、Ajax Get 異步請求
console.log("請求前:" + new Date().getTime());
AjaxGet("http://192.168.1.116:8080/data/get?a=1", function(data){
console.log("result3",data);
document.getElementById("result3").innerText=data;
});
console.log("請求后:" + new Date().getTime());
// 4、Ajax Ajax Post 異步請求
console.log("請求前:" + new Date().getTime());
AjaxPost("http://192.168.1.116:8080/data/post?a=1", "key=value", function(data){
console.log("result4",data);
document.getElementById("result4").innerText=data;
});
console.log("請求后:" + new Date().getTime());
</script>
</body>
</html>
jQuery的Ajax同步&異步代碼案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery的Ajax同步&異步代碼案例</title>
<script src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<div>
<span id="result1"></span>
<hr/>
<span id="result2"></span>
<hr/>
<span id="result31"></span>
<hr/>
<span id="result32"></span>
<hr/>
<span id="result41"></span>
<hr/>
<span id="result42"></span>
</div>
<script type="text/javascript">
// 1、Ajax Get同步請求
let result1=$.ajax({
type: 'get',
url: 'http://192.168.1.116:8080/data/get',
async:false,
headers:{'token':'1333333333'},
});
console.log("result1",result1.responseText);
$("#result1").text(result1.responseText);
// 2、Ajax Post 同步請求
let result2=$.ajax({
type: 'post',
url: 'http://192.168.1.116:8080/data/post',
data: {},
async:false,
headers:{'token':'1333333333'},
});
console.log("result2",result2.responseText);
$("#result2").text(result2.responseText);
// 3、Ajax Get 異步請求
$.get("http://192.168.1.116:8080/data/get", function(data,status){
console.log("result31", JSON.stringify(data));
$("#result31").text(JSON.stringify(data));
});
$.ajax({
type: 'get',
url: 'http://192.168.1.116:8080/data/get',
async: true,
headers:{'token':'1333333333'},
success: function (res){
console.log("result32", JSON.stringify(res));
$("#result32").text(JSON.stringify(res));
},
error:function(err){
console.log("error32", err);
}
});
// 4、Ajax AjaxPost 異步請求
$.post("http://192.168.1.116:8080/data/post",{ id:''},function(data){
console.log("result41", JSON.stringify(data));
$("#result41").text(JSON.stringify(data));
});
$.ajax({
type: 'post',
url: 'http://192.168.1.116:8080/data/post',
data:{ id:'' },
contentType: 'application/x-www-form-urlencoded',
async: false,
headers:{'token':'1333333333'},
success: function (res){
console.log("result42", JSON.stringify(res));
$("#result42").text(JSON.stringify(res));
},
error:function(err){
console.log("error42", err);
}
});
</script>
</body>
</html>
Axios的Ajax同步&異步代碼案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Axios的Ajax同步&異步代碼案例</title>
<script src="https://lib.baomitu.com/axios/0.21.4/axios.min.js"></script>
</head>
<body>
<div>
<span id="result11"></span>
<hr/>
<span id="result12"></span>
<hr/>
<span id="result21"></span>
<hr/>
<span id="result22"></span>
<hr/>
<span id="result31"></span>
</div>
<script type="text/javascript">
// URL編碼 URL解碼
console.log("URL編碼",encodeURIComponent("名字"));
console.log("URL解碼",decodeURIComponent("%E5%90%8D%E5%AD%97"));
// 1、Ajax Get異步請求
axios.get('http://192.168.1.116:8080/data/get?id=11&name=名字',{
params: {desc:"描述"},
headers: {"token": "token123"}
}).then(res=> {
console.log("result11", JSON.stringify(res.data));
document.getElementById("result11").innerText=JSON.stringify(res.data);
});
// 另外一種寫法
axios({
url: 'http://192.168.1.116:8080/data/get?id=12&name=名字',
method: 'GET',
params: {desc:"描述"},
headers: {"token": "token123"}
}).then(res=> {
console.log("result12", JSON.stringify(res.data));
document.getElementById("result12").innerText=JSON.stringify(res.data);
})
// 2、Ajax Post異步請求
axios.post('http://192.168.1.116:8080/data/post',"id=21&name=名字",{
headers: {"token": "token123"}
}).then(res=> {
console.log("result21", JSON.stringify(res.data));
document.getElementById("result21").innerText=JSON.stringify(res.data);
})
// 另外一種寫法
axios({
url: 'http://192.168.1.116:8080/data/post',
method: 'post',
data: {id: 22,name:'名字'},
headers: {"token": "token123"}
}).then(res=> {
console.log("result22", JSON.stringify(res.data));
document.getElementById("result22").innerText=JSON.stringify(res.data);
});
// 3、Ajax Get同步請求
console.log("請求前:" + new Date().getTime());
async function getData() {
let data="";
await axios.get('http://192.168.1.116:8080/data/get?id=31&name=名字').then(res=> {
data=JSON.stringify(res.data);
console.log("執行1:" + new Date().getTime());
});
console.log("執行2:" + new Date().getTime());
return data;
}
const result=getData();
result.then(res=>{
console.log("執行3:" + new Date().getTime());
console.log("result31", res);
document.getElementById("result31").innerText=res;
})
console.log("請求后:" + new Date().getTime());
</script>
</body>
</html>
SpringBoot后臺代碼
跨域的Filter:
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD");
response.setHeader("Access-Control-Max-Age", "3600");
//response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
response.setHeader("Access-Control-Allow-Headers", "*");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
配置(主要是跨域):
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CommonConfig {
@Bean
public FilterRegistrationBean registerAuthFilter() {
FilterRegistrationBean registration=new FilterRegistrationBean();
registration.setFilter(new SimpleCORSFilter());
registration.addUrlPatterns("/*");
registration.setName("simpleCORSFilter");
registration.setOrder(1); // 值越小,Filter越靠前。
return registration;
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration=new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); //允許任何域名
corsConfiguration.addAllowedHeader("*"); //允許任何頭
corsConfiguration.addAllowedMethod("*"); //允許任何方法
return corsConfiguration;
}
// @Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); //注冊
return new CorsFilter(source);
}
}
Controller支持:
jQuery 底層 AJAX 實現。簡單易用的高層實現見 $.get, $.post, $.getJSON, $getScript。使用該方法進行異步數據通訊可以很靈活地設置請求的各個參數。常用參數和說明:
參數 | 描述 |
url | 發送請求的地址 |
data | 發送到服務器的數據。將自動轉換為請求字符串格式。 |
type | 請求方式 ("POST" 或 "GET"), 默認為 "GET" |
dataType | 預期服務器返回的數據類型。可用值: xml,html,script,json,jsonp,text |
success | 請求成功后的回調函數。參數:由服務器返回,并根據dataType參數進行處理后的數據 |
error | 默認: 自動判斷 (xml 或 html)) 請求失敗時調用此函數。如果發生了錯誤,錯誤信息(第二個參數)除了得到null之外,還可能是"timeout", "error", "notmodified" 和 "parsererror" |
async | 默認設置下,所有請求均為異步請求。如果需要發送同步請求,請將此選項設置為 false。注意,同步請求將鎖住瀏覽器,用戶其它操作必須等待請求完成才可以執行 |
示例:
$.ajax({ type: "POST", url: "testServlet", data: {"name":"itcast","location":"guangzhou"}, success: function(msg){ alert( "Data Saved: " + msg ); } }); |
*請認真填寫需求信息,我們會在24小時內與您取得聯系。