AJAX请求

代码示例1:

jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
	<style type="text/css">
		body{
			width: 400px;
			text-align: right;
		}
	</style>
<script type="text/javascript" src="${pageContext.request.contextPath}/jquery-1.7.2.js"></script>
<script type="text/javascript">
	/* ajax异步请求 */
	$(function(){
		$("[name=cardId]").blur(function(){
			$.post("${pageContext.request.contextPath}/UserServlet",{"cardId":$(this).val(),"method":"backJson"},function(data){
				if(data){
					//字符串转成json 
					//var json= JSON.parse(data);
					console.log(data.cardId);
					$("#span").text("身份证号["+data.cardId+"]已存在");
				}else{
					$("#span").text("身份证号可使用");
				}
			},"json");
		})
	})
</script>
</head>
<body>
<h1>账号注册</h1>
<form action="${pageContext.request.contextPath}/UserServlet?method=regist" method="post">
	身份证号:<input type="text" name="cardId" value="${param.cardId}"/><br/>
	<span id="span"></span><br/>
	用户名:<input type="text" name="name" value="${param.name}"/><br/>
	密码:<input type="text" name="password" value="${param.password}"/><br/>
	确认密码:<input type="text" name="qrpwd" value="${param.qrpwd}"/><br/>
	<input type="submit" value="注册">
	<input type="button" value="返回" onclick="window.location.href='http://localhost:8080/family_work/login.jsp'"/>
	<p>${msg}</p>
</form>
</body>
</html>

servlet页面:

protected void backJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	User bean = WEBUtils.getRequestBean(request, User.class);
	User user = us.login(bean);
	if(user!=null){
	//对象序列化为json字符串,方法省略
		String jsonStr = GsonUtils.objectToJsonStr(user);
		response.getWriter().print(jsonStr);
	}
}

代码示例2:

基于restful风格的批量删除操作:

js代码:

<script type="application/javascript">
   $(function () {
       $("#btn").click(function () {
           var idArrs = new Array();
           //var pageNumber=${page.pageNumber}
          $("input[name=check]:checked").each(function (i) {
               idArrs[i]=$(this).val();
           })
          /*for(var i=0;i<$("input[name=check]:checked").length;i++){
              idArrs[i]=$("input[name=check]:checked").eq(i).val();
          }*/
           if(idArrs.length==0){
               alert("至少要选中一笔资料");
               return;
           }
          if(confirm("确定要删除掉勾选内容吗?")){
              $.ajax({
                  url : "http://localhost:8080/product/delProduct" ,   // 处理的请求路径
                  type : "POST" ,    // 此处发送的是post请求(可变更为其他需要的请求)
                  /*contentType: 'application/json',*/
                  data: {_method:"DELETE",idArrs:idArrs},
                  dataType : "json" , // 返回的数据类型为json类型
                  success : function(data) {
                      //console.log(data);
                    if(data==="success"){
                       // window.location.href="${pageContext.request.contextPath }/product/pageAll.html?pageNumber="+pageNumber;
                        //window.location.href=window.location.href
                        //window.location.reload(true);
                        //location.replace(location.href);
                        //window.location=window.location
                        $("input[name=check]:checked").each(function () {
                            $(this).parent().parent().parent().remove();//移除选中的tr
                        })
                        $("#msg").text("删除成功!").css("color","green");

                    }else{
                        $("#msg").text("删除失败!").css("color","red");
                    }
                  }
              });
           }
       })
       //全选操作,属性中带有true,false;例如:checked,selected,用prop方法。
       //除以上用prop方法之外,都用attr方法。attr方法在执行一次全选,全不选之后,不会再次执行全选操作。
       $("#all").click(function () {
          if($("input[name=check]:checkbox").is(":checked")){
              $("input[name=check]:checkbox").prop("checked",false);
          }else{
              $("input[name=check]:checkbox").prop("checked",true);
          }

       })
   })
 </script>

jsp:

<div class="BatchOperation fl">
    <label  id="all" class="btnStyle middle">全选</label>
    <input type="button" value="批量删除" class="btnStyle" id="btn"/>
</div>

controller:

@RequestMapping(value = "/delProduct",method = RequestMethod.DELETE)
    @ResponseBody
    public Object delProduct(@RequestParam(value="idArrs[]") String [] idArrs){
        String jsonString="";
        int count = productService.delProduct(idArrs);
        if(count<0) {
            jsonString = JSON.toJSONString(Constants.ERROR_MESSAGE);//此处可以“error”替换
            return jsonString;
        }else {
            jsonString = JSON.toJSONString(Constants.SUCCESS_MESSAGE);//此处可以用“success”替换
            return jsonString;
        }
    }

mapper.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "http://mybatis.org/dtd/mybatis-3-mapper.dtd" "mybatis-3-mapper.dtd" >
<mapper namespace="cn.wedding.mapper.product.ProductMapper">
    <delete id="delProduct" parameterType="string" >
        delete from productinfo where productId in
        <foreach collection="array" item="ids" open="(" separator="," close=")">
            #{ids}
        </foreach>
    </delete>
</mapper>

web.xml:

<!-- method方法过滤 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值