springMvc+AJAX+JSON的增刪改查


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'list.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->

<script type="text/javascript">

//點擊兩次可以關閉窗口
var flag=true;
function a(){
if(flag){
document.getElementById("addDiv").style.display='none';
flag=false;
}else{
document.getElementById("addDiv").style.display='block';
flag=true;
}
}


//封裝了重復的代碼 rul:請求的路徑 methodType:請求的方式 param:參數 retnFunction:請求有返回的結果的回調函數
function sendAjax(url,methodType,param,retnFunction){
var xmlhttp=null;
//兼容所有的瀏覽器 創建XHR對象
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
retnFunction(xmlhttp.responseText);
}
}

if(methodType=="get"||methodType=="GET"){
xmlhttp.open("GET",url+"?"+param,true);
xmlhttp.send();
}else{
xmlhttp.open("POST",url,true);
//charset=UTF-8 解決亂碼問題
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send(param);
}
}

//查詢和刪除
function query() {
var foodname=document.getElementsByName("foodName")[0].value;
sendAjax("${pageContext.request.contextPath}/popo","GET","foodname="+foodname,function(responseText){
var resultJson=responseText; //返回一個json字符串
//轉化為json對象 返回為一個集合
var resultObj=JSON.parse(resultJson);
//獲取表格id為myTable對象
var table=document.getElementById("myTable");
//獲取所有的name為dataTr的tr
var allDataTr=document.getElementsByName("dataTr");
for(var i=0;allDataTr.length;i++){
//數組是動態變化的 刪了第一個 第二個會變成第一個
table.removeChild(allDataTr[0]);//防止第二次查詢展示出重復的數據
}

//展示查詢的結果
for(var i=0;i<resultObj.length;i++){
var obj=resultObj[i];

//獲取td對象
var td=document.createElement("td");
//設值
td.innerText=obj.foodName;
var td1=document.createElement("td");
td1.innerText=obj.price;
//獲取一個td對象
var td2=document.createElement("td");

//刪除按鈕
var ib=document.createElement("button");
ib.innerText="刪除";
td2.appendChild(ib);

//修改按鈕
var ib1=document.createElement("button");
ib1.innerText="修改";
td2.appendChild(ib1);



//獲取tr對象
var tr=document.createElement("tr");
//把獲取的對象綁定在button按鈕上
ib.foodObj=obj;
//把tr綁定在button按鈕上
ib.myLineTr=tr;
//刪除的事件
ib.addEventListener("click",function(){
//獲取當前按鈕
var eventSrc=event.srcElement;
table.removeChild(eventSrc.myLineTr);

sendAjax("${pageContext.request.contextPath}/deleteFood/"+eventSrc.foodObj.foodid,"POST","_method=delete",function(responseText){
if(responseText==1){
alert("刪除成功");
}else{
alert("刪除失敗");
}
})
});


//修改的事件
ib1.foodObj=obj;
ib1.addEventListener("click",function(){
//獲取當前按鈕
var eventSrc=event.srcElement;
//顯示窗口
document.getElementById('updateDiv').style.display='block';
document.getElementsByName("umyFoodName")[0].value=eventSrc.foodObj.foodName;
document.getElementsByName("umyFoodPrice")[0].value=eventSrc.foodObj.price;
document.getElementsByName("umyFoodid")[0].value=eventSrc.foodObj.foodid;
});
//給tr標簽設一個標識
tr.setAttribute("name","dataTr");
//在tr追加td
tr.appendChild(td);
tr.appendChild(td1);
tr.appendChild(td2);
//把tr追加到table后
table.appendChild(tr);
}
});
}

//新增
function saveFood(){
var myFoodName=document.getElementsByName("myFoodName")[0].value;
var myFoodPrice=document.getElementsByName("myFoodPrice")[0].value;
sendAjax("${pageContext.request.contextPath}/saveFood","POST","foodname="+myFoodName+"&price="+myFoodPrice,function(responseText){
if(responseText==1){
alert("新增成功");
document.getElementById('addDiv').style.display='none';
query();
}else{
alert("新增失敗");
}
});
}

function updateFood(){
var umyFoodName=document.getElementsByName("umyFoodName")[0].value;
var umyFoodPrice=document.getElementsByName("umyFoodPrice")[0].value;
var umyFoodid=document.getElementsByName("umyFoodid")[0].value;

sendAjax("${pageContext.request.contextPath}/updateFood/"+umyFoodid,"POST","_method=put&foodname="+umyFoodName+"&price="+umyFoodPrice,function(responseText){
if(responseText==1){
alert("修改成功");
document.getElementById('updateDiv').style.display='none';
query();
}else{
alert("修改失敗");
}
});
}
</script>

</head>

<body>
<input type="text" name="foodName">
<input type="button" value="提交" onclick="query()"> <input type="button" value="新增" onclick="a()">
</body>

<table id="myTable">
<tr><th>菜品名</th><th>菜品價格</th><th>操作</th></tr>
</table>

<!-- 新增彈出的窗口 -->
<div id="addDiv" style="display:none;position:absolute;left:40%;top:40%;z-index:100;border:1px solid black; width:200px;height:200px">
              新增<br/>
菜品名:<input type="text" name="myFoodName"/><br/>
價格:<input type="text" name="myFoodPrice"/><br/>
<input type="button" value="保存" onclick="saveFood()"/><input type="button" value="關閉" onclick="a()"/>
</div>

<!-- 修改彈出的窗口 -->
<div id="updateDiv" style="display:none;position:absolute;left:40%;top:40%;z-index:100;border:1px solid black; width:200px;height:200px">
              修改<br/>
<input type="hidden" name="umyFoodid"/>
菜品名:<input type="text" name="umyFoodName"/><br/>
價格:<input type="text" name="umyFoodPrice"/><br/>
<!-- onclick點擊事件關閉窗口 -->
<input type="button" value="確定" onclick="updateFood()"/><input type="button" value="關閉" onclick="document.getElementById('updateDiv').style.display='none'"/>
</div>
</html>


cltroller層


package cn.et.springmvc.lesson06.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

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

import cn.et.springmvc.lesson06.dao.MyFoodDapImpl;

@Controller
public class MyFoodController {
@Autowired
MyFoodDapImpl mdi;
//查詢
@RequestMapping(value="/popo",method=RequestMethod.GET)
public String queryFood(String foodname, OutputStream os) throws UnsupportedEncodingException, IOException{
List<Map<String, Object>> queryAllFood = mdi.queryAllFood(foodname);
JSONArray arry=JSONArray.fromObject(queryAllFood);
String j=arry.toString();
os.write(j.getBytes("UTF-8"));
return null;
}

//刪除
@RequestMapping(value="/deleteFood/{foodid}",method=RequestMethod.DELETE)
public String deleteFood(@PathVariable String foodid, OutputStream os) throws UnsupportedEncodingException, IOException{
try{
mdi.deleteFood(foodid);
os.write("1".getBytes("UTF-8"));
}catch(Exception e){
os.write("0".getBytes("UTF-8"));
}
return null;
}


//修改
@RequestMapping(value="/updateFood/{foodid}",method=RequestMethod.PUT)
public String updateFood(@PathVariable String foodid,String foodname,String price, OutputStream os) throws UnsupportedEncodingException, IOException{
try{
mdi.updateFood(foodid, foodname, price);
//返回以代表成功
os.write("1".getBytes("UTF-8"));
}catch(Exception e){
//返回0代表失敗
os.write("0".getBytes("UTF-8"));
}
return null;
}


//增加
@RequestMapping(value="/saveFood",method=RequestMethod.POST)
public String saveFood(String foodname,String price, OutputStream os) throws UnsupportedEncodingException, IOException{
try{
mdi.saveFood(foodname, price);
os.write("1".getBytes("UTF-8"));
}catch(Exception e){
os.write("0".getBytes("UTF-8"));
}
return null;
}
}
dao層

package cn.et.springmvc.lesson06.dao;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class MyFoodDapImpl {
@Autowired
JdbcTemplate jdbc;
public List<Map<String, Object>> queryAllFood(String foodname){
String sql="select * from food where foodName like '%"+foodname+"%'";
return jdbc.queryForList(sql);
}

public void deleteFood(String foodid){
String sql="delete from food where foodid="+foodid;
jdbc.execute(sql);
}

public void saveFood(String foodname,String price){
String sql="insert into food(foodName,price) values('"+foodname+"','"+price+"')";
jdbc.execute(sql);
}

public void updateFood(String foodid,String foodname,String price){
String sql="update food set foodName='"+foodname+"',price='"+price+"' where foodid="+foodid;
jdbc.execute(sql);
}
}

---------------------
原文:https://blog.csdn.net/panhaigang123/article/details/78595575


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM