JQuery?AJAX操作代碼
1、服務(wù)器端
1.1、創(chuàng)建web項(xiàng)目
在項(xiàng)目根目錄下創(chuàng)建js文件夾并將JQuery文件放入其中:
1.2、服務(wù)器端代碼
封裝返回結(jié)果的實(shí)體類(lèi):
public class Result { private Integer code;//錯(cuò)誤碼 private String msg;//提示信息 private String data;//具體內(nèi)容 //…… getter/setter方法、默認(rèn)構(gòu)造方法、全參構(gòu)造方法 @Override public String toString() { //返回JSON字符串 return "{\"Result\":{" + "\"code\":" + code + ",\"msg\":\"" + msg + '\"' + ",\"data\":\"" + data + '\"' + "}}"; } }
處理前端頁(yè)面請(qǐng)求的Servlet
@WebServlet(urlPatterns = "/demoServlet") public class DemoServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { ServletInputStream is = request.getInputStream(); String str = inputStream2String(is); PrintWriter out = response.getWriter(); out.write("server received data is :" + str); out.flush(); out.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException { String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); PrintWriter out = response.getWriter(); out.write(new Result(200, "OK", name + ":" + pwd).toString()); out.flush(); out.close(); } public String inputStream2String(InputStream is) { //字節(jié)流轉(zhuǎn)為字符流 try (BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));) { StringBuffer buffer = new StringBuffer(); String line = ""; while ((line = in.readLine()) != null) { buffer.append(line); } return buffer.toString(); } catch (IOException e) { e.printStackTrace(); } return null; } }
2、客戶端
2.1、$.ajax([options])
jQuery 底層 AJAX 實(shí)現(xiàn),其返回其創(chuàng)建的 XMLHttpRequest 對(duì)象。大多數(shù)情況下無(wú)需直接操作該函數(shù),除非需要操作不常用的選項(xiàng),以獲得更多的靈活性。 $.ajax()
方法的參數(shù)是一個(gè)鍵值對(duì)形式的JSON對(duì)象。最簡(jiǎn)單的情況下, $.ajax()
可以不帶任何參數(shù)直接使用。
如果要處理$.ajax()得到的數(shù)據(jù),則需要使用回調(diào)函數(shù):
- beforeSend:在發(fā)送請(qǐng)求之前調(diào)用,并且傳入一個(gè)XMLHttpRequest作為參數(shù)。
- error:在請(qǐng)求出錯(cuò)時(shí)調(diào)用(比如:服務(wù)器端出錯(cuò)拋出異常)。傳入XMLHttpRequest對(duì)象,描述錯(cuò)誤類(lèi)型的字符串以及一個(gè)異常對(duì)象(如果有的話)
- dataFilter:在請(qǐng)求成功之后調(diào)用。傳入返回的數(shù)據(jù)以及"dataType"參數(shù)的值。并且必須返回新的數(shù)據(jù)(可能是處理過(guò)的)傳遞給success回調(diào)函數(shù)。
- success:當(dāng)請(qǐng)求之后調(diào)用(只要求請(qǐng)求成功,不管服務(wù)器端的業(yè)務(wù)是否成功)。傳入返回后的數(shù)據(jù),以及包含成功代碼的字符串。
- complete:當(dāng)請(qǐng)求完成之后調(diào)用這個(gè)函數(shù),無(wú)論成功或失敗。傳入XMLHttpRequest對(duì)象,以及一個(gè)包含成功或錯(cuò)誤代碼的字符串。
常用的options有:
- async:(默認(rèn): true) 默認(rèn)設(shè)置下,所有請(qǐng)求均為異步請(qǐng)求。如果需要發(fā)送同步請(qǐng)求,請(qǐng)將此選項(xiàng)設(shè)置為 false。注意,同步請(qǐng)求將鎖住瀏覽器,用戶其它操作必須等待請(qǐng)求完成才可以執(zhí)行。
- type:請(qǐng)求方式, 默認(rèn)為 “GET”。注意:其它 HTTP 請(qǐng)求方法,如 PUT 和 DELETE 也可以使用,但僅部分瀏覽器支持。
- url:(默認(rèn): 當(dāng)前頁(yè)地址) 發(fā)送請(qǐng)求的地址。
- contentType:(默認(rèn): “application/x-www-form-urlencoded”) 發(fā)送信息至服務(wù)器時(shí)內(nèi)容編碼類(lèi)型。默認(rèn)值適合大多數(shù)情況。
- data:發(fā)送到服務(wù)器的數(shù)據(jù)。將自動(dòng)轉(zhuǎn)換為請(qǐng)求字符串格式。GET 請(qǐng)求中將附加在 URL 后。必須為 Key/Value 格式。如果為數(shù)組,jQuery 將自動(dòng)為不同值對(duì)應(yīng)同一個(gè)名稱(chēng)。如 {foo:[“bar1”, “bar2”]} 轉(zhuǎn)換為 ‘&foo=bar1&foo=bar2’。
- dataType:預(yù)期服務(wù)器返回的數(shù)據(jù)類(lèi)型。如果不指定,jQuery 將自動(dòng)根據(jù) HTTP 包 MIME 信息來(lái)智能判斷??捎弥?
- “text”: 返回純文本字符串
- “json”: 返回 JSON 數(shù)據(jù) 。
- “xml”: 返回 XML 文檔,可用 jQuery 處理。
- “html”: 返回純文本 HTML 信息;包含的script標(biāo)簽會(huì)在插入dom時(shí)執(zhí)行。
- “script”: 返回純文本 JavaScript 代碼。不會(huì)自動(dòng)緩存結(jié)果。除非設(shè)置了"cache"參數(shù)。’’‘注意:’’'在遠(yuǎn)程請(qǐng)求時(shí)(不在同一個(gè)域下),所有POST請(qǐng)求都將轉(zhuǎn)為GET請(qǐng)求。(因?yàn)閷⑹褂肈OM的script標(biāo)簽來(lái)加載)
- “jsonp”: JSONP 格式。使用 JSONP 形式調(diào)用函數(shù)時(shí),如 “myurl?callback=?” jQuery 將自動(dòng)替換 ? 為正確的函數(shù)名,以執(zhí)行回調(diào)函數(shù)。
示例:
前面頁(yè)面代碼:
<%@ page pageEncoding="UTF-8" %> <html> <head> <script src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript"> $(function () { $("#btn1").click(function () { $.ajax({ async:true, type:'GET', url:'${pageContext.request.contextPath}/demoServlet', data:{'name':'zhangsan','pwd':'1234'}, dataType:'json', success:function (data) { console.info(data); }, error:function () { console.info("請(qǐng)求失敗"); } }); }); $("#btn2").click(function () { $.ajax({ type:"POST", url:'${pageContext.request.contextPath}/demoServlet', data:"HelloWorld", dataType:'text', success:function (data) { console.info(data); } }) }); }); </script> </head> <body> <button id="btn1">Get請(qǐng)求后臺(tái)數(shù)據(jù)</button> <button id="btn2">Post請(qǐng)求后臺(tái)數(shù)據(jù)</button> </body> </html>
運(yùn)行
單擊"Get請(qǐng)求后臺(tái)數(shù)據(jù)",結(jié)果:
單擊"Post請(qǐng)求后臺(tái)數(shù)據(jù)",結(jié)果:
2.2、$…get(url, [data], [callback], [type])
通過(guò)遠(yuǎn)程 HTTP GET 請(qǐng)求載入信息。參數(shù)
- url:待載入頁(yè)面的URL地址
- data: (可選)待發(fā)送 Key/value 參數(shù)。
- callback :(可選)載入成功時(shí)回調(diào)函數(shù)。
- type: (可選)返回內(nèi)容格式,xml, html, script, json, text, _default。
示例:
前端頁(yè)面代碼:
<%@ page pageEncoding="UTF-8" %> <html> <head> <script src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript"> $(function () { $("#btn1").click(function () { $.get('${pageContext.request.contextPath}/demoServlet', {'name': 'zhangsan', 'pwd': '1234'}, function (data) { console.info(data); }, 'json' ); }); </script> </head> <body> <button id="btn1">Get請(qǐng)求后臺(tái)數(shù)據(jù)</button> </body> </html>
2.3、$.getJSON(url, [data], [callback])
通過(guò) HTTP GET 請(qǐng)求載入 JSON 數(shù)據(jù)。
參數(shù)
- url:發(fā)送請(qǐng)求地址。
- data :(可選)Map待發(fā)送 Key/value 參數(shù)。
- callback :(可選)載入成功時(shí)回調(diào)函數(shù)。
示例:
前端頁(yè)面代碼:
<%@ page pageEncoding="UTF-8" %> <html> <head> <script src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript"> $(function () { $("#btn1").click(function () { $.getJSON('${pageContext.request.contextPath}/demoServlet', {'name': 'zhangsan', 'pwd': '1234'}, function (data) { console.info(data); } ); }); </script> </head> <body> <button id="btn1">Get請(qǐng)求后臺(tái)數(shù)據(jù)</button> </body> </html>
2.4、$.post(url, [data], [callback], [type])
通過(guò)遠(yuǎn)程 HTTP POST 請(qǐng)求載入信息。參數(shù)
- url:發(fā)送請(qǐng)求地址。
- data:(可選)待發(fā)送 Key/value 參數(shù)。
- callback: (可選)發(fā)送成功時(shí)回調(diào)函數(shù)。
- type:(可選)返回內(nèi)容格式,xml, html, script, json, text, _default。
示例:
前面頁(yè)面代碼:
<%@ page pageEncoding="UTF-8" %> <html> <head> <script src="${pageContext.request.contextPath}/js/jquery.js"></script> <script type="text/javascript"> $("#btn2").click(function () { $.post('${pageContext.request.contextPath}/demoServlet',"HelloWorld", function (data) { console.info(data); }, 'text' ) }); }); </script> </head> <body> <button id="btn2">Post請(qǐng)求后臺(tái)數(shù)據(jù)</button> </body> </html>
注意
使用AJAX時(shí)可能會(huì)報(bào)這樣的警告:
Synchronous XMLHttpRequest on the main thread is deprecated
原因是ajax執(zhí)行了同步操作,即async設(shè)置為False,當(dāng)然它并不影響程序的運(yùn)行,但建議還是改成True為好(不設(shè)置默認(rèn)為T(mén)rue)。
到此這篇關(guān)于JQuery AJAX的文章就介紹到這了,更多相關(guān)JQuery AJAX內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
jquery ajax傳遞中文參數(shù)亂碼問(wèn)題及解決方法說(shuō)明
本篇文章主要是對(duì)jquery ajax傳遞中文參數(shù)亂碼問(wèn)題及解決方法進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助2014-02-02jQuery Timelinr實(shí)現(xiàn)垂直水平時(shí)間軸插件(附源碼下載)
jquery.timelinr.js是一款效果非常炫酷的jQuery時(shí)間軸插件。下面腳本之家小編給大家介紹jQuery Timelinr實(shí)現(xiàn)垂直水平時(shí)間軸插件,需要的朋友參考下2016-02-02jQuery實(shí)現(xiàn)的簡(jiǎn)單手風(fēng)琴效果示例
這篇文章主要介紹了jQuery實(shí)現(xiàn)的簡(jiǎn)單手風(fēng)琴效果,結(jié)合實(shí)例形式分析了jQuery基于事件響應(yīng)、頁(yè)面元素屬性動(dòng)態(tài)操作實(shí)現(xiàn)手風(fēng)琴效果的方法,需要的朋友可以參考下2018-08-08jquery插件制作 表單驗(yàn)證實(shí)現(xiàn)代碼
今天的內(nèi)容是關(guān)于表單驗(yàn)證插件的制作。表單驗(yàn)證控件實(shí)現(xiàn)的主要功能是,當(dāng)表單提交的時(shí)候檢查必填項(xiàng)是否正確填寫(xiě),同時(shí)根據(jù)需要驗(yàn)證輸入信息是否符合規(guī)范2012-08-08省市區(qū)三級(jí)聯(lián)動(dòng)jquery實(shí)現(xiàn)代碼
這篇文章主要為大家詳細(xì)紹了省市區(qū)三級(jí)聯(lián)動(dòng)jquery實(shí)現(xiàn)代碼,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10