AJAX_idea

来源:互联网 发布:淘宝买家怎么提升等级 编辑:程序博客网 时间:2024/06/16 21:16
JSP的添加






<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>test</title>
    <!-- Bootstrap -->

    <script src="../js/jquery.min.js"></script>

</head>

<body>
<script type="text/javascript">
    function send() {
        var content = $("#content").val();
        content = encodeURI(content);
        var chk_value = [];
        $("input[name='uid']:checked").each(function () {
            chk_value.push($(this).val())
        });
        var chec = chk_value.toString();
        chec = encodeURI(chec);

        var jinji;
        $("input[name='payMethod']:checked").each(function () {
            jinji=($(this).val())
        });

        $.ajax({
            type: "get",
            url: "/user/insert.action",//需要用来处理ajax请求的action
            data: {content: content, chec: chec, jinji:jinji},
            dataType: "json",//设置需要返回的数据类型
            success: function (data) {
                /* if(data != null)
                 {
                     alert("成功");
                 }*/
                var count = data.count;
                if (count == 1) {
                    alert("注册成功")
                    $(":checkbox").removeAttr("checked");
                    $("#content").val("");
                    $(":radio").removeAttr("checked");
                }
            },
            error: function () {
                alert("系统异常,请稍后重试!");
            }
        });
    }

</script>
<form action="/user/insert.action" method="post">
    请选择联系人:

    <c:forEach items="${list}" var="li">
        <input type="checkbox" value="${li.uid}" name="uid" id="name">${li.uname}
    </c:forEach>
    <br>
    请输入消息内容:<textarea name="content" id="content" cols="30" rows="10"></textarea>
<%--    请输入消息内容:<input type="text" name="content" id="content"><br>--%>
    <input type="radio" name="payMethod" value="1" />爱理不理
    <input type="radio" name="payMethod" value="2" />看一下就好
    <input type="radio" name="payMethod" value="3" />十万火急
    <br>
    <br>
    <br>
    <input type="button" value="发送" onclick="send()" id="send()">
    <a href="/user/selectAll.action"><input type="button" value="查看站内信息"/></a>
</form>
</body>
</html>




JSP的查询







<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>test</title>
    <script src="../js/jquery.min.js"></script>
    <script type="text/javascript">
$(function () {
    $("#selectOne").blur(function(){
        var content=$(this).val();
     /*var rr=$("option[name='aa']:checked").val();*/
        content=encodeURI(content);

        alert(content);
        if(content!=null) {
            $.ajax({
                type: "get",
                url: "/user/selectOne.action",//需要用来处理ajax请求的action
                data: {content: content},
                dataType: "json",//设置需要返回的数据类型
                success: function (data) {
                    var list = data.list;
                    if (list != null) {
                        alert("成功")
                        var str = "";
                        for (var i = 0; i < list.length; i++) {
                            str += "<tr id=" + list[i].mid + ">" +
                                "<td>" + "<input type='checkbox' name='ids' value='" + list[i].mid + "' id='ch'>" + "</td>" +
                                "<td class='mi'>" + list[i].mid + "</td>" +
                                "<td>" + list[i].content + "</td>" +
                                "<td>" + list[i].cretetime + "</td>" +
                                "<td>" + list[i].rank + "</td>" +
                                "<td>" + list[i].u_id + "</td>" +


                                "<td>" + "<input type='button' value='删除' onclick='shan(" + list[i].mid + ")' class='sh'>" + "</td>" +
                                "</tr>";
                        }

                        $("#tbody").html(str);
                    }
                },
                error: function () {
                    alert("系统异常,请稍后重试!");
                }
            });
        }else{
            alert("bu neng wei kong")
        }

    })
    $("#deleteAll").click(function(){
        var array=new Array();
        $("input[type=checkbox]:gt(0):checked").each(function(){
            array.push($(this).parent().next().text());
        });
        console.log(array);
        location.href="/user/batchDelete.action?ids="+array;
    });
    $("#selectAll").click(function(){
        $("input[type=checkbox]:gt(0)").each(function () {
            if ($(this).prop("checked")) {
                $(this).removeAttr("checked");
            } else {
                $(this).prop("checked", 'true');
            }
        });

    });
        $(".cha").change(function(){
           var pp=$(this).val();
            /!* var pp=$("option[name='aa']:checked").val();*!/
            pp=encodeURI(pp);
            var op=pp.toString();
            $.ajax({
                type: "get",
                url: "/user/selectByName.action",//需要用来处理ajax请求的action
                data: {op: op},
                dataType: "json",//设置需要返回的数据类型
                success: function (data) {
                    var list = data.list;

                    if (list!= null) {
                        alert("成功")
                        var str = "";
                        for (var i = 0; i < list.length; i++) {
                            str += "<tr id=" + list[i].mid + ">" +
                                "<td>" + "<input type='checkbox' name='ids' value='" + list[i].mid + "' id='ch'>" + "</td>" +
                                "<td class='mi'>" + list[i].mid + "</td>" +
                                "<td>" + list[i].content + "</td>" +
                                "<td>" + list[i].cretetime + "</td>" +
                                "<td>" + list[i].rank + "</td>" +
                                "<td>" + list[i].u_id + "</td>"+


                                "<td>" + "<input type='button' value='删除' onclick='shan(" + list[i].mid + ")' class='sh'>" + "</td>" +
                                "</tr>";
                        }
                        $("#tbody").html(str);
                    }
                },
                error: function () {
                    alert("系统异常,请稍后重试!");
                }
            });

        })

})
        function shan(mid) {
            $.ajax({
                type: "get",
                url: "/user/delete.action",//需要用来处理ajax请求的action
                data: "mid=" + mid,
                dataType: "json",//设置需要返回的数据类型
                success: function (data) {
                    var count = data.count;
                    if (count == 1) {
                        $("#" + mid).remove();
                    }
                },
                error: function () {
                    alert("系统异常,请稍后重试!");
                }
            });

        }

    </script>
</head>

<body>



<select  name="u_id"  class="cha">
    <option value="syyh" name="aa">所有用户</option>
    <c:forEach items="${list }" var="Type">
        <option value="${Type.uid }" name="aa">${Type.uname }</option>

    </c:forEach>
</select>
你可以用来模糊查询:<input type="text" id="selectOne" />
<table border="1" width="400" border="0" cellspacing="0" cellpadding="0" id="ta">
    <tr>
        <td><input type="checkbox" id="selectAll" /></td>
        <td>消息Id</td>
        <td>消息内容</td>
        <td>时间</td>
        <td>紧急程度</td>
        <td>接收人</td>
        <td>操作</td>
    </tr>
    <tbody id="tbody">
    <c:forEach items="${list2}" var="li">
        <tr id="5"></tr>
        <tr id="${li.mid}">
            <td><input type="checkbox"/></td>
            <td class="mi">${li.mid}</td>
            <td>${li.content}</td>
            <td>${li.cretetime}</td>
            <td>${li.rank}

                <c:if test="${li.rank==101}">爱理不理</c:if>
          <c:if test="${li.rank==202}">看一下就好</c:if>
                 <c:if test="${li.rank==303}">十万火急</c:if>

            </td>
            <td>
                <c:if test="${li.u_id==1}">唐太宗</c:if>
                <c:if test="${li.u_id==2}">汉武帝</c:if>
                <c:if test="${li.u_id==3}">秦始皇</c:if>
                <c:if test="${li.u_id==4}">成吉思汗</c:if>
                <c:if test="${li.u_id==5}">武则天</c:if>


            </td>
            <td>
                <input type="button" value="删除" onclick="shan(${li.mid})" class="sh">
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
<input type="button" value="批量删除" id="deleteAll"/>

</body>
</html>






controller






package com.bawei.controller;

import com.bawei.pojo.Message;
import com.bawei.pojo.User;
import com.bawei.service.MessageService;
import com.bawei.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Controller
    @RequestMapping("user")
    public class UserController {
        @Autowired
        private UserService service;
        @Autowired
        private MessageService mservice;

        @RequestMapping("selectAll")
        public String selectAll(Model model) {
            System.out.print("进入查询全部方法");
            List<User> list = service.selectAll();
            model.addAttribute("list", list);
            List<Message> list2=mservice.getMessageList();
            model.addAttribute("list2",list2);
              return "selectList";
        }
    @RequestMapping(value = "/imgUpload",method = RequestMethod.POST )
    public String imgUpload(MultipartFile  image, HttpServletRequest req, HttpServletResponse res) throws IOException {
        Map<String,Object> map = new HashMap<>();
        System.out.println("----- 插入图片 -------");
System.out.println(image.getBytes()+""+image.getOriginalFilename()+""+image.getBytes());
System.out.println(!image.isEmpty());
if(!image.isEmpty()){
    byte[] bytes=image.getBytes();
    return "redirect:uploadSuccess";
}else{
    return "redirect:uploadSuccess";
}
    }

    @RequestMapping(value = "login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(User user,HttpSession session,Model model){
        Map<String,Object> map = new HashMap<>();
        try {

            System.out.print("进入了登录方法");
            user = service.login(user);
            session.setAttribute("user", user);
            int count = 1;
            map.put("count",count);
            return map;
        } catch (Exception e) {
            System.out.print("出错了");
         return map;
        }
    }

    @RequestMapping( value = "/selectOne",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object>selectOne(String content)throws Exception {
        content=URLDecoder.decode(content,"utf-8");
        System.out.print(content);
        Map<String,Object> map=new HashMap<String,Object>();
        Message msg=new Message();
        List<Message> list=mservice.selectOne(content);
        map.put("list",list);
        return map;
        }

    @ResponseBody
    @RequestMapping( value = "/selectByName",method = RequestMethod.GET)
    public Map<String,Object>selectByName(String op,HttpSession session,HttpServletRequest request)throws Exception {
           op=URLDecoder.decode(op,"utf-8");
           System.out.print("jing re cha xun jie mian ");
Map<String,Object> map=new HashMap<String,Object>();
Map<String,String> result =new LinkedHashMap<String,String>();

result.put("101","爱理不理");
result.put("202","看一下就好");
result.put("303","十万火急");
        request.setAttribute("resultMap",result);
Message msg=new Message();
if(op.equals("syyh")){
List<Message> list=mservice.getMessageList();
map.put("list",list);
}else{
    String uid=op;
   List<Message> list=mservice.selectByName(Integer.parseInt(uid));
    map.put("list",list);
        }
        return map;
    }
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> delete(String mid) throws Exception {
        Map<String, Object> map = new HashMap<>();
        Message msg = new Message();
        msg.setMid(Integer.parseInt(mid));
        String id=mid;
         mservice.delete(Integer.parseInt(id));
         int count=1;
        map.put("count", count);
        return map;
    }
    @RequestMapping("batchDelete")
    public String batchDelete(String[] ids){
        for (String string : ids) {
            mservice.delete(Integer.parseInt(string));
        }
        return "index";
    }
      @RequestMapping("selectUserList")
      public String selectUserList(Model model) {
          System.out.print("jint ren fang fa ");
          List<User> list = service.selectAll();
          model.addAttribute("list", list);
          return "insert";
      }
        @RequestMapping( value = "/insert",method = RequestMethod.GET)
        @ResponseBody
        public Map<String,Object> insert(String content,String chec ,int jinji)throws Exception {

           Map<String,Object> map=new HashMap<>();
           content= URLDecoder.decode(content,"utf-8");
           chec=URLDecoder.decode(chec,"utf-8");
           Message msg;
    for (String arg:chec.split(",")) {
        msg = new Message();
        msg.setContent(content);
        msg.setRank(jinji);
        msg.setU_id(Integer.parseInt(arg));
        mservice.insert(msg);
    }
     int count=1;
    map.put("count",count);
            return map;
        }
/*@RequestMapping("batchInsert")
    public String batchInsert(String[] ids){
    for (String  string : ids) {
        mservice.insert(string);
    }
}*/



    }




原创粉丝点击