旅遊管理開發(三)模態框修改,添加操做

1.project_edit.jshtml

$(document).ready(function () {
//綁定點擊事件
$("#modal-dialog").on("click",".ok",saveOrUpdate);

//當彈框被隱藏時執行的函數
$("#modal-dialog").on("hidden.bs.modal",function () {
//當彈框被隱藏時執行的函數
$("#modal-dialog").off("click",".ok");
$("#modal-dialog").removeData("id");
});

var id = $("#modal-dialog").data("id");
if(id){//若是有值說明單機的是修改按鈕
findProjectById(id);
}


})

//修改彈框獲取值
function findProjectById(id) {
var url = "project/findProjectById";
var params = {"id":id};
$.getJSON(url,params,function (result) {
if(result.state == 1){//查詢成功
//給彈框賦值
initFormDate(result.data);
}else{
alert(result.message);
}
});
}

//初始話彈窗的數據
function initFormDate(project){
$("#nameId").val(project.name);
$("#codeId").val(project.code);
$("#beginDateId").val(project.beginDate);
$("#endDateId").val(project.endDate);
$("input[type='radio']").each(function () {
//設置選中狀態
if(project.status == $(this).val()){//判斷狀態值
$(this).prop("checked",true);
}
});


$("#endDateId").val(project.endDate);
}

//添加或者修改項目數據
function saveOrUpdate() {
//驗證表單數據是否爲空
if(!$("#editFormId").valid()){//表單爲空返回false
return;
}

//獲取表單數據
var params = {
name:$("#nameId").val(),
code:$("#codeId").val(),
beginDate:$("#beginDateId").val(),
endDate:$("#endDateId").val(),
remarks:$("#remarks").val(),
status:$("input[type='radio']:checked").val()
};
// console.log(params);
//異步提交數據
var saveUrl = "project/saveProject";
var updateUrl = "project/updateProject";

//從模態框取出id判斷當前操做是新增仍是修改
var id = $("#modal-dialog").data("id");
var url = (id?updateUrl:saveUrl);

if(id){
params.id = id;
}else{
alert("模態框當前id不存在")
}

$.post(url,params,function (result) {
if(result.state == 1){
alert(result.message);
$("#modal-dialog").modal("hide");
findAllObject();
} else{
alert(result.message);
}
});


}

  2.project_listjava

// $(document).read(function () {
//     //調用
//     findAllObject();
// })

$(function () {
    findAllObject();

    //單擊事件
    //獲取表單對象
    $("#queryFormId").on("click",".btn-search",doQueryObject);
    $("#queryFormId").on("click",".btn-invalid,.btn-valid",updateStatusById);

    //綁定添加按鈕
    $("#queryFormId").on("click",".btn-add",loadEditPage);

    //在修改按鈕上綁定一個事件
    $("#queryFormId").on("click",".btn-info",loadEditPage);

})

//add編輯頁面
function loadEditPage() {
    //顯示編輯頁面
    var url = "project/editUI";
    var title;

    if($(this).hasClass("btn-add")){
        title = "添加項目信息";
    }else if($(this).hasClass("btn-info")){
        title = "修改項目信息";
        //修改按鈕父親是td,td父親是tr
        var ValueId = $(this).parent().parent().data("id");
        $("#modal-dialog").data("id",ValueId);
    }

    //在彈框中異步加載顯示編輯頁面
    $("#modal-dialog .modal-body").load(url,function () {
        //頁面加載完成後顯示彈框
        //方法傳入show表示顯示,傳入hide表示隱藏
        $(".modal-title").html(title);
        $("#modal-dialog").modal("show");
    });
}

//禁用啓用項目信息
function updateStatusById(){

    //獲取當前點擊按鈕是啓用仍是禁用
    // var clazz = $(this).attr("class");
    // if(clazz == "btn btn-primary btn-invalid"){}
    var status;
    if($(this).hasClass("btn-invalid")){
        status = 0;
    }
    if($(this).hasClass("btn-valid")){
        status = 1;
    }
    //獲取選中的複選框id的值
    var ids = "";
    $("#tbodyId input[name='checkId']").each(function () {
        //獲取全部的複選框進行遍歷
        //判斷哪一個被選中
        if($(this).prop("checked")){//若是結果爲true,表明當前遍歷到的複選框被選中
            if(ids == ""){
                ids += $(this).val();
            }else{
                ids += ","+$(this).val();
            }
        }
    })

    if(ids==""){
        alert("😙親,請至少選用一條記錄!");
        return;
    }

    var url = "project/updateStatusById";
    var params={"status":status,"ids":ids};
    //發送異步請求,更新數據
    $.post(url,params,function (result) {
        if(result.state == 1){
            alert(result.message);
            findAllObject();
        }else{
            alert(result.message);
        }
    });
}

function doQueryObject(){//按條件查詢
    //先初始化頁碼
    $("pageId").data("pageCurrent",1);
    findAllObject();
}

function findAllObject() {
    // var url = "project/findAllProject";
    var url = "project/findPageObject";
    var pageCurrent = $("#pageId").data("pageCurrent");
    if(!pageCurrent){
        pageCurrent = 1;
    }
    var params = {"pageCurrent":pageCurrent};
    params.name = $("#searchNameId").val();
    params.status = $("#searchValidId").val();
    $.getJSON(url,params,function (result) {

        setTableBodyRows(result.data.list);//查詢數據

        setPagination(result.data.pageObject);//分頁

    });
}

function setTableBodyRows(result){
    //1.先獲取tbody對象
    var tbody = $("#tbodyId");
    tbody.empty();//清空數據爲了防止還保留着之前的數據
    //2. 循環數據result
    for(var i in result){
        //3.建立一個tr對象,用來顯示每行數據
        var tr = $("<tr></tr>");
        //給tr綁定id值
        tr.data("id",result[i].id);
        //var td = $("<td></td>")
        //td.append(result[i].id)
        //4.建立每行的td對象(一行有多個數據)
        //5.在td對象內部填充查詢出來的具體數據
        var td = "<td><input type='checkbox' name='checkId' value="+result[i].id+" /></td>"
            +"<td>"+result[i].code+"</td>"
            +"<td>"+result[i].name+"</td>"
            +"<td>"+result[i].beginDate+"</td>"
            +"<td>"+result[i].endDate+"</td>"
            //				+"<td>"+new Date(result[i].beginDate).toLocaleDateString()+"</td>"
            //				+"<td>"+new Date(result[i].endDate).toLocaleDateString()+"</td>"
            +"<td>"+(result[i].status==1?'有效':'無效')+"</td>"
            +"<td><input type='button' class='btn btn-info btn-warning' value='修改' /></td>";

        //6.將建立出來的td對象添加到tr對象當中去
        tr.append(td);
        //7.將建立出來的tr對象添加到tbody中
        tbody.append(tr);
    }
}

  3.projectMapper.xmlweb

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.tanzhou.tzms.product.dao.ProjectDao">
    <!-- 抽取重複代碼 -->
    <sql id="whereQuery">
        <where><!-- 將條件前多餘的and或者or去掉 -->
            <if test = "name!=null and name != ''">
                name like concat("%",#{name},"%")
            </if>
            <if test = "status!=null">
                and status = #{status}
            </if>
        </where>
    </sql>

    <!-- public List<Project> findAllProject(); -->
    <select id="findAllProject" resultType="com.tanzhou.tzms.product.domain.Project">
		SELECT id,code,name,beginDate,endDate,status,remarks,createdTime,
		modifiedTime,createdUser,modifiedUser FROM tz_projects
	</select>

<!--    public List<Project> findPageObject(-->
<!--    @Param("startIndex") int startIndex,-->
<!--    @Param("pageSize") int pageSize,-->
<!--    @Param("name") String name,-->
<!--    @Param("status") Integer status);-->
    <select id="findPageObject" resultType="com.tanzhou.tzms.product.domain.Project">
        SELECT id,code,name,beginDate,endDate,status,remarks,createdTime,modifiedTime,createdUser,modifiedUser FROM tz_projects
        <include refid="whereQuery"></include><!-- 重複代碼塊複用 -->
        ORDER BY beginDate DESC LIMIT #{startIndex},#{pageSize}
    </select>


    <!-- public int getRowCount();  -->
    <update id="updateProject">
        update tz_projects
        <set>
            <if test="code != null and code != ''">
                code = #{code}
            </if>
            <if test="name != null and name != ''">
                ,name = #{name}
            </if>
            <if test="beginDate != null and beginDate != ''">
                ,beginDate = #{beginDate}
            </if>
            <if test="endDate != null and endDate != ''">
                ,endDate = #{endDate}
            </if>
            <if test="status != null and status != ''">
                ,status = #{status}
            </if>
            <if test="remarks != null and remarks != ''">
                ,remarks = #{remarks}
            </if>
            , modifiedTime = now()
        </set>

        where id = #{id}
    </update>
    <!--
    public Integer updateStatusById(Integer status,String[] Ids); -->
    <select id="getRowCount" resultType="int">
        SELECT COUNT(*) FROM tz_projects
        <include refid="whereQuery"></include><!-- 重複代碼塊複用 -->
    </select>
<!--    public Project findProjectById(Integer id);-->
    <select id="findProjectById" resultType="com.tanzhou.tzms.product.domain.Project">
        select * from tz_projects where id = #{id}
    </select>

    <!--    public Integer updateProject(Project project);-->
    <update id = "updateStatusById">
        update tz_projects set status=#{status} where id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </update>

    <!--
    public Integer insertProject(Project project); -->
    <insert id="insertProject">
		insert into tz_projects(code,name,beginDate,endDate,remarks,createdTime,createdUser,modifiedTime,modifiedUser)
		values(#{code},#{name},#{beginDate},#{endDate},#{remarks},now(),#{createdUser},now(),#{modifiedUser})
	</insert>

</mapper>

  4.projectServiceImpl.javaspring

package com.tanzhou.tzms.product.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tanzhou.tzms.common.exception.ServiceException;
import com.tanzhou.tzms.common.web.PageObject;
import com.tanzhou.tzms.product.dao.ProjectDao;
import com.tanzhou.tzms.product.domain.Project;
import com.tanzhou.tzms.product.service.ProjectService;
@Service("projectService")
public class ProjectServiceImpl implements ProjectService{

    @Autowired
    private ProjectDao projectDao;

    public List<Project> findAllProject() {
        return projectDao.findAllProject();
    }

    /**
     * 分頁須要返回兩個數據,一個是查詢出來的當前數據,一個是分頁的數據
     */
    public Map<String,Object> findPageObject(int currentPage,String name,Integer status) {

        //頁面顯示條數
        int pageSize = 5;
        Integer startIndex = (currentPage - 1) * pageSize;
        System.out.println("pageSize---"+pageSize+"  startIndex---"+startIndex);

        //獲取當前頁面數據
        List<Project> findPageObject = projectDao.findPageObject(startIndex, pageSize,name,status);
        System.out.println("findPageObjectIMPL當前頁數據條數------>"+findPageObject.size());

        //獲取總條數
        int rowCount = projectDao.getRowCount(name,status);
        System.out.println("獲取總條數"+rowCount);

        //計算總頁數
//		int pageCount;
//		if(rowCount%2 == 0) {
//			pageCount = rowCount/2;
//		}else {
//			pageCount = rowCount/2;
//			pageCount += 1;
//		}

        //封裝分頁信息
        PageObject page = new PageObject();
        page.setRowCount(rowCount);//總條數
        page.setPageSize(pageSize);//每一頁顯示的數據
        page.setPageCurrent(currentPage);//選擇的頁數(用戶傳遞)
        page.setStartIndex(startIndex);//查詢數據開始

        //把當前數據以及分頁信息封裝到map進行返回
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("list",findPageObject);
        map.put("pageObject",page);
        return map;
    }

    @Override
    public Integer updateStatusById(Integer status, String ids) {
        //ids:1,2,3-->數組
        if(ids.length() == 0 && ids.equals("")) {
            throw new ServiceException("ids的值不能爲空");
        }

        String[] idArray = ids.split(",");

        if(status != 0 && status != 1) {
            throw new ServiceException("狀態值不合法");
        }

        return projectDao.updateStatusById(status,idArray);
    }

    @Override
    public void saveProject(Project project) {
        if(project == null)
            throw new ServiceException("保存對象不能爲空");
        Integer rows = projectDao.insertProject(project);
        System.out.println("新增行數==="+rows);
        if(rows <= 0) {
            throw new ServiceException("新增失敗 ");
        }
    }

    @Override
    public void updateProject(Project project) {
        if(project == null){
            throw new ServiceException("修改對象不能爲空");
        }
        Integer rows = projectDao.updateProject(project);
        if(rows <= 0){
            throw new ServiceException("修改失敗");
        }
    }

    @Override
    public Project findProjectById(Integer id) {
        if(id ==null){
            throw new ServiceException("修改對象不能爲空");
        }
        Project project = projectDao.findProjectById(id);
        if(project == null){
            throw new ServiceException("對象不存在");
        }
        return project;
    }


}

  5.projectController.javasql

package com.tanzhou.tzms.product.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tanzhou.tzms.common.web.JsonResult;
import com.tanzhou.tzms.product.domain.Project;
import com.tanzhou.tzms.product.service.ProjectService;

@Controller
@RequestMapping("/project")
public class ProjectController {
	
	@Autowired
	private ProjectService projectService;
	
	/**
	 * 返回項目管理頁面
	 * @return
	 */
	@RequestMapping("/listUI")
	public String listUI(){
		return "product/project_list";//項目列表頁面
	}
	
	/**
	 * 項目管理下的首頁展現數據
	 */
	@RequestMapping("/findAllProject")
	@ResponseBody
	public List<Project> findAllProject(){
		System.out.println("全部數據");
		List<Project> list = projectService.findAllProject();
		return list;//轉成json[{"id":1,"name":"日本遊"...},{}]
	}
	
//	@RequestMapping("/findPageObject")
//	@ResponseBody
//	/**
//	 * {
//	 * 	"list":[{id:1,name:"長沙遊"}]
//	 * 	"page":[pageCount:1,pageCount:2]
//	 * }
//	 * @return
//	 */
//	public Map<String,Object> findPageObject(Integer pageCurrent,String name,Integer status){
//		Map<String, Object> map = projectService.findPageObject(pageCurrent,name,status);
//		return map;
//	}
	

	/**
	 * {
	 * 	
	 * }
	 * @return
	 */
	/*
	 {
	 	status:1
	 	message:"ok"
	 	data:{
	 		"list":[{id:1,name:"長沙遊"}]
	 		"page":[pageCount:1,pageCount:2]
	 	}
	 }
	  */
	@RequestMapping("/findPageObject")
	@ResponseBody
	public JsonResult findPageObject(Integer pageCurrent, String name, Integer status){
		System.out.println(pageCurrent+"===="+name+"========"+status);
		Map<String, Object> map = projectService.findPageObject(pageCurrent,name,status);
		return new JsonResult(map);
//		return map;
	}
	
//	/**
//	 * 狀態更新
//	 */
//	@RequestMapping("/updateStatusById")
//	@ResponseBody
//	public void updateStatusById(Integer status, String ids) {
//		projectService.updateStatusById(status, ids);
//	}
	//重構
	/**
	 * 狀態更新
	 */
	/**
	 * 
	 * 正確:
	 * {
	 * 		status:1
	 * 		message:"啓用成功或者禁用成功失敗"
	 * 		data:
	 * }
	 * 出現異常:
	 * {
	 * 		status:0
	 * 		message:"狀態值不合法"
	 * 		data:
	 * }
	 * @param status
	 * @param ids
	 * @return
	 */
	@RequestMapping("/updateStatusById")
	@ResponseBody
	public JsonResult updateStatusById(Integer status, String ids) {
		projectService.updateStatusById(status, ids);
		return new JsonResult(status==1?"啓用成功":"禁用成功");
	}
	
	/**
	 * 新增
	 * @param project
	 * @return
	 */
	@RequestMapping("/saveProject")
	@ResponseBody
	public JsonResult saveProject(Project project){
		projectService.saveProject(project);
		//springmvc底層獲取到的參數數據,會對數據進行解析
		//調用參數project對象的set的方法將數據封裝到project對象中去
		return new JsonResult("新增成功");
	}
	
	/**
	 * 用於顯示編輯頁面
	 */
	@RequestMapping("/editUI")
	public String editUI() {
		return "product/project_edit";
	}

	/**
	 * 修改項目信息
	 */
	@RequestMapping("/updateProjet")
	@ResponseBody
	public JsonResult updateProjet(Project project){
		projectService.updateProject(project);
		return new JsonResult("修改爲功");
	}

	/**
	 * 根據id拿到數據
	 * @param id
	 * @return
	 */
	@RequestMapping("findProjectById")
	@ResponseBody
	public JsonResult findProjectById(Integer id){
		return new JsonResult(projectService.findProjectById(id));
	}
}

  

相關文章
相關標籤/搜索