用例 1:用戶注冊
用戶填完注冊用戶后,使用 Ajax 技術實現對用戶名的重復驗證
* * * * *
提示
~~~
//用戶名驗證
$("#uname").blur(function(){
//用戶名
var uname = $("#uname").val().trim();
//用戶名不能為空
if(uname==""){
$("#uname+span").html("用戶名不能為空");
$("#uname+span").css("color","red");
checkUname = false;
}else{
$.ajax({
type:"post",
url:"servlet/RegisterSerlvet",
data:{"way":"checkName","uname":uname},
success:function(data){
//用戶名已存在
if(data=="1"){
$("#uname+span").html("用戶名已存在");
$("#uname+span").css("color","red");
checkUname = false;
//用戶名可用
}else if(data=="2"){
$("#uname+span").html("√");
$("#uname+span").css("color","green");
checkUname = true;
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert("請求失敗!");
}
});
}
});
~~~
用例 2:購物車功能的實現
~~~
//獲取當前頁被選中書籍id的數組
function getSelect(){
//存放id的數組
var arr = [];
$("#tbody :checkbox").each(function() {
if((this.checked)) {
arr.push(this.value);
}
});
return arr;
}
~~~
~~~
/**
* 添加商品到購物車
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void doUpdateShop(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
// 獲取選中書籍id數組
String[] selectorId = request.getParameterValues("selector");
ShopServiceImpl ssi = new ShopServiceImpl();
// 獲取當前用戶名
String uname = (String) request.getSession().getAttribute("uname");
// 實例化書籍service類
BookServiceImpl bsi = new BookServiceImpl();
// 循環遍歷數組,判斷有無存在與購物車
for (String s : selectorId) {
int bid = Integer.parseInt(s);
// 獲取對應bid的書籍
Book book = bsi.getBook(bid);
// 單價
Double price = book.getPrice();
// true代表存在于購物車
if (ssi.ifInShop(bid, uname)) {
// 獲取對應的購物書籍
Shop shop = ssi.getShop(bid, uname);
// 已購數量
int count = shop.getCount();
// 執行更新
ssi.updateShop(bid, count + 1, (count + 1) * price, uname);
} else {
// 執行新增
ssi.insertShop(bid, 1, price, uname);
}
}
}
~~~