用例 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);
}
}
}
~~~