前端代码
$(".mod_post").click(function (e) {
var id = $(".id").val(),
name = $(".name").val(),
english = $(".english").val(),
chinese = $(".chinese").val(),
math = $(".math").val(),
total = $(".total").val();
var map_data_o = {};
var old_data = new Map();
var new_data = new Map();
if (id != idc) {
new_data.set("id", id);
} else {
old_data.set("id", idc);
map_data_o["id"]=idc;
}
if (name != namec) {
new_data.set("name", name);
} else {
old_data.set("name", namec);
}
if (chinese != chinesec) {
new_data.set("chinese", chinese);
} else {
old_data.set("chinese", chinesec);
}
if (math != mathc) {
new_data.set("math", math);
} else {
old_data.set("math", mathc);
}
if (english != englishc) {
new_data.set("english", english);
} else {
old_data.set("english", englishc);
}
if (total != totalc) {
new_data.set("total", total);
} else {
old_data.set("total", totalc);
}
console.log(new_data);
new_data.set("null","null");
//为了区分新数据和老数据的分界线,
//因为数据一旦用json传输的话就会把map转换为数组所以需要用这个来区分新数据和老数据
console.log(old_data);
// JSON.parse(JSON.stringify(new_data));
// JSON.parse(JSON.stringify(old_data));
console.log(JSON.parse(JSON.stringify(new_data)));
console.log(JSON.parse(JSON.stringify(old_data)));
$.ajax({
type: "post",
url: "/servlet_mod",
data:{
// n:Array.from(new_data),
// o:Array.from(old_data)
n:Array.from(new_data),
o:Array.from(old_data)
},
dataType: "json",
success: function (response) {
}
});
})
后端代码
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
@WebServlet("/servlet_mod")
public class Mod_server_ajax extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map map = req.getParameterMap();
Map n_val=new HashMap();
Map o_val=new HashMap();
boolean n_or_o= true;
//遍历
for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry element = (Map.Entry) iter.next();
//key值
//Object strKey = element.getKey();//获取的是o[0][] 或者是n[1][]的数据键值
//value,数组形式的值,但是因为前端是map的原因所以0的位置存的是key 1的位置存的是value
String[] value = (String[]) element.getValue();
if (value[0].equals("null") && value[1].equals("null")) {
n_or_o = false;
continue;
}
if (n_or_o) {
n_val.put(value[0],value[1]);
} else {
o_val.put(value[0],value[1] );
}
}
Iterator it=n_val.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
String value= n_val.get(key);
System.out.printf("%s : %sn",key,value);
}
it=o_val.keySet().iterator();
while (it.hasNext()){
String key = it.next();
String value= o_val.get(key);
System.out.printf("%s : %sn",key,value);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}