1. 程式人生 > >web前端——ajax提交後臺controller實現前端後臺互動(1) 傳單個引數

web前端——ajax提交後臺controller實現前端後臺互動(1) 傳單個引數

ajax傳單個引數給controller(action)

<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
    function del(gid) {
        $.ajax({
            type: "post",
            url: "/goods/del",
            data: "gid="+gid,
            dataType:'text', //需要的是text格式
            //contextType:'application/json;charset=UTF-8',這句也不需要
            async: false,
            success:function(callbackdata){
                alert("success");
            },
            error:function (data, status, e){
                alert("error");
            }
        });
    };
</script>
</head>
<body>
    <div> 
    <c:forEach items="${goodsList}" var="goodItem">
     <div>
         <input onclick="del('${goodItem.id}');" type="submit" value="刪除"/>
     </div>
    </c:forEach>
    <div>
</body>

controller中:

@RequestMapping("/del")
public String del(@RequestParam("gid")long gid, Model model){
    if(String.valueOf(gid)!=null &&String.valueOf(gid)!=""){
        System.out.println("gid="+gid);
        goodsService.del(gid);
    }
    else{
        System.out.print("controller del gid為空");
    }
    List<Goods> goodsList=goodsService.findAll();
    model.addAttribute("goodsList",goodsList);
    return "goodsList";
}

service直接呼叫dao,在此略。。。
dao中:

 public void delete(long id) {
    String hql="delete from Goods g where g.id="+id;
    Query query=sessionFactory.getCurrentSession().createQuery(hql);
    query.executeUpdate();
}