AJAX在JQuery中的應(yīng)用詳解
AJAX在jQuery中的應(yīng)用
1. $.ajax()方法
$.ajax()方法是一個功能十分強(qiáng)悍的一個底層方法,基于該方法實現(xiàn)的$.get()和$.post()都是常用的向服務(wù)器請求數(shù)據(jù)的方法。
1.1 $.ajax()中的參數(shù)及使用方法
$.ajax()調(diào)用的語法格式為:
$.ajax([options])
其中,可選參數(shù)[options]作為$.ajax()方法中的請求設(shè)置,其格式為key/value,既包含發(fā)送請求的參數(shù),也含有服務(wù)器響應(yīng)回調(diào)的數(shù)據(jù),常用的參數(shù)具體格式如下:
1.2 $.ajax()方法的使用實例
實例中使用的是一個簡單的基于SSH框架的Java Web項目
這里我們通過一個controller來接受一個UserEntity類型的數(shù)據(jù),然后返回一個Map類型的數(shù)據(jù),實現(xiàn)頁面的請求。
@Controller @RequestMapping("/user") public class UserController { @Resource private IUserService userService; @ResponseBody @RequestMapping(value="/login", method = RequestMethod.POST) public Map<String,Object> login(UserEntity user){ Map<String,Object> map = new HashMap<String,Object>(); System.out.println(user.toString()); //判斷數(shù)據(jù)庫中是否存在這樣一個UserEntity數(shù)據(jù) boolean loginResult = userService.isExist(user); map.put("loginResult", loginResult); return map; } }
前端代碼:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>" rel="external nofollow" > <title>用戶登錄</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="<%=basePath %>css/bootstrap.css" rel="external nofollow" > </head> <body> <div> <div class="input-group"> <span class="input-group-addon" id="name_span">UserName</span> <!--從這里輸入一個username--> <input name="username" type="text" class="form-control" placeholder="UserName" aria-describedby="name_span"> </div> <div class="input-group"> <span class="input-group-addon" id="password_span">PassWord</span> <!--從這里輸入一個password--> <input name="password" type="password" class="form-control" placeholder="PassWord" aria-describedby="password_span"> </div> <!--提交表單--> <input type="submit" id="loginBtn" class="btn btn-default" value="Login" /> </div> </body> <script type="text/javascript" src="<%=basePath %>js/jquery-2.1.4.js"></script> <script type="text/javascript" src="<%=basePath %>js/login.js"></script> </html>
為了方面講解,我們將AJAX代碼單獨放到了一個js文件中
$(function() { $("#loginBtn").click(function() { console.log("login"); var username = $("input[name=username]").val(); var password = $("input[name=password]").val(); var user = { "username" : username, "password" : password }; $.ajax({ type : "post", dataType : "json", data : user, contentType : "application/x-www-form-urlencoded;charset=UTF-8", url : "user/login", async : false, success : function(data) { if (false == data.loginResult) { alert("用戶名或者密碼錯誤,請重新登錄!"); } else if (true == data.loginResult) { alert("登錄成功!"); var indexUrl = window.location.protocol+"http://"+window.location.host+window.location.pathname+"html/index.html"; window.location = indexUrl; } }, error : function() { alert("服務(wù)器發(fā)生故障,請嘗試重新登錄!"); } }); }); });
上述js代碼中,在data部分構(gòu)造了一個user對象,通過post方法傳遞給服務(wù)器時,服務(wù)器會將其解析成一個UserEntity類型的user對象(神奇吧,具體的原理我暫時也不是很懂,希望明白人在微博下方留言,不吝賜教)。當(dāng)contentType
設(shè)置成"application/x-www-form-urlencoded;charset=UTF-8"
時,提交的是一個from表單,而不是我們常用的json對象,但是服務(wù)器返回的是一個json對象。然后我們在success
后面的函數(shù)中對返回的數(shù)據(jù)進(jìn)行了解析(一個布爾類型的數(shù)據(jù)),根據(jù)結(jié)構(gòu)進(jìn)行了簡單的跳轉(zhuǎn)。
2. 其他請求服務(wù)器數(shù)據(jù)的方法
$.get()方法和$.post()方法都是基于$.ajax()方法實現(xiàn)的向服務(wù)器請求數(shù)據(jù)的方法,使用起來比起$.ajax()方法更加簡便,需要設(shè)置的參數(shù)更少,但是我們更多時候使用的仍然是$.ajax()方法,因為它的可定制程度更高,更加的靈活易用。
2.1 $.get()方法
$.get([options])
該方法在傳入options時,只需要簡單的是設(shè)置好url、date、success等選項即可。例如
$.get( "/user/login", {name: encodeURI($("#username").val()}, function(data){ ....省略邏輯代碼 } )
由于get方法向服務(wù)器發(fā)送請求時,使用K/V格式,如果參數(shù)中含有中文字符,需要通過encodeURI()
來進(jìn)行轉(zhuǎn)碼。
2.2 $.post()方法
$.post([options])
.post()方法的使用和.post()方法的使用和.get()方法基本一致,事例如下:
$.post( "/user/login", {name: encodeURI($("#username").val()}, function(data){ ....省略邏輯代碼 } )
同樣是在參數(shù)中含有中文字符時,需要使用encodeURI()
進(jìn)行轉(zhuǎn)碼操作
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
相關(guān)文章
jquery 插件實現(xiàn)多行文本框[textarea]自動高度
這篇文章主要介紹了jquery 插件實現(xiàn)多行文本框[textarea]自動高度,需要的朋友可以參考下2015-03-03JQuery 引發(fā)兩次$(document.ready)事件
ASP.net MVC 做了個工程,不知道為什么Search按就總是執(zhí)行兩次。2010-01-01jquery Deferred 快速解決異步回調(diào)的問題
下面小編就為大家?guī)硪黄猨query Deferred 快速解決異步回調(diào)的問題。小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-04-04利用jQuery treetable實現(xiàn)樹形表格拖拽詳解
這篇文章主要為大家介紹了如何利用jQuery treetable實現(xiàn)樹形表格拖拽功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以動手嘗試一下2022-06-06