一.什么是AJAX
1.Ajax概念
Ajax 是Web 开发一个流行的词汇,全称 Asynchronous JavaScript and XML(json,yml),异步的JavaScript和XML 。是几种技术的强强联合
2.Ajax如何工作
Ajax(即异步 JavaScript 和 XML)是一种 Web 应用程序开发的手段,它采用客户端脚本与Web 服务器交换数据。
3.为什么要学习Ajax
使用Ajax的最大优点,就是能在不更新整个页面的前提下维护数据。这使得Web应用程序更为迅捷地回应用户动作,并避免了在网络上发送那些没有改变过的信息
二.json的应用
常用的几种json:
1.阿里巴巴 fastjson
2.谷歌Gson
3.SpringMvc内嵌的JackSon
4.Json-lib
简单的Json-lib Java应用
在pom.xml引入json-lib的架包
<!-- 引入json-lib的架包 -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
测试
package springmvc.less06.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class Test {
/**注意
* json字符串的键 一定带 "key":1
* 值数字不需要"" 字符串必须带
*/
//将对象转换成json{"username":"A","usid":1}
public static void parseObject(){
Map map= new HashMap();
map.put("usid", 1);
map.put("username", "A");
//将Java转换成json
JSONObject jo=JSONObject.fromObject(map);
System.out.println(jo.toString());
}
//{"username":"A","ma":{"stree":"gl","city":"sz"},"usid":1}
public static void parsejsonArray(){
Map map= new HashMap();
map.put("usid", 1);
map.put("username", "A");
Map ma= new HashMap();
ma.put("city", "sz");
ma.put("stree", "gl");
map.put("ma", ma);
//将Java转换成json
JSONObject jo=JSONObject.fromObject(map);
System.out.println(jo.toString());
}
//将数组转换成json[{"username":"A","usid":1},{"username":"B","usid":2}]
public static void parseAray(){
Map map= new HashMap();
map.put("usid", 1);
map.put("username", "A");
Map ma= new HashMap();
ma.put("usid", 2);
ma.put("username", "B");
List list= new ArrayList();
list.add(map);
list.add(ma);
//将Java数组转换成json
JSONArray ja=JSONArray.fromObject(list);
System.out.println(ja.toString());
}
public static void main(String[] args) {
parseAray();
}
}
Js的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">
function query(){
//无刷新调用http://..获取到数据数据通过动dom方式添加到 table
//ajax(异步的ajax)+json
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");
}
//接收open产生的关联,回调函数
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//返回的是字符串的json
var resutJson=xmlhttp.responseText;
//转换为接js对象
var resutObj=JSON.parse(resutJson);
//获取表格对象
var table=document.getElementById("myTable");
//将所有名字为dataTr的tr全部删除
var allDateTr=document.getElementsByName("dataTr");
var length=allDateTr.length;
for(var i=0;i<length;i++){
table.removeChild(allDateTr[0]);
}
for(var i=0;i<resutObj.length;i++){
var obj=resutObj[i];
var tr=document.createElement("tr");
var td=document.createElement("td");
td.innerText=obj.foodname;
var td1=document.createElement("td");
td1.innerText=obj.price;
tr.setAttribute("name","dataTr");
//追加到table
tr.appendChild(td);
tr.appendChild(td1);
table.appendChild(tr);
}
}
} //获取文本框传过来的值
var foodname=document.getElementsByName("foodname")[0].value;
//open表示产生一个请求的关联(get提交)
xmlhttp.open("GET","${pageContext.request.contextPath}/queryFood?foodname="+foodname,true);
xmlhttp.send();
}
</script>
</head>
<body>
<input type="text" name="foodname" />
<input type="button" value="查询" οnclick="query()"/>
<table id="myTable">
<tr><th>菜品名</th><th>菜品价格</th></tr>
</table>
</body>
</html>
servlet层
package springmvc.less06.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 MyFoodDaoImpl {
@Autowired
JdbcTemplate jdbc;
//根据菜名查询所有
public List<Map<String,Object>> selectFood(String foodname){
return jdbc.queryForList("select * from food where foodname like '%"+foodname+"%'");
}
//根据id删除
public void deleteFood(String foodid){
jdbc.execute("delete from food where foodid ="+foodid);
}
//新增
public void saveFood(String foodname,String price){
jdbc.execute("insert into food(foodname,price) values('"+foodname+"','"+price+"')");
}
//修改
public void updateFood(String foodid,String foodname,String price){
jdbc.execute("update food set foodname='"+foodname+"',price='"+price+"' where foodid="+foodid);
}
}
controller层
//自动装配实现类
@Autowired
MyFoodDaoImpl mfi;
//根据名称查询
@RequestMapping(value="/queryFood",method=RequestMethod.GET)
public String quer(String foodname,OutputStream os)throws Exception{
//获取所有数据
List<Map<String,Object>> aur =mfi.selectFood(foodname);
//转换成json
JSONArray array= JSONArray.fromObject(aur);
String jst=array.toString();
//输出
os.write(jst.getBytes("UTF-8"));
return null;
}
三.ajax的增删改查
在mvc-servlet.xml中配置json消息转换器
<!-- 将springmvc注解的action交给springmvc处理 国际化验证需要配置validator-->
<mvc:annotation-driven validator="localValidatorFactoryBean">
<mvc:message-converters>
<!-- 配置json消息转换器 -->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<!-- 设置响应支持的类型 -->
<value>text/html</value>
<!-- 设置请求body支持的类型 -->
<value>application/x-www-form-urlencoded</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
业务逻辑层
package springmvc.less06.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 MyFoodDaoImpl {
@Autowired
JdbcTemplate jdbc;
//根据菜名查询所有
public List<Map<String,Object>> selectFood(String foodname){
return jdbc.queryForList("select * from food where foodname like '%"+foodname+"%'");
}
//根据id删除
public void deleteFood(String foodid){
jdbc.execute("delete from food where foodid ="+foodid);
}
//新增
public void saveFood(String foodname,String price){
jdbc.execute("insert into food(foodname,price) values('"+foodname+"','"+price+"')");
}
//修改
public void updateFood(String foodid,String foodname,String price){
jdbc.execute("update food set foodname='"+foodname+"',price='"+price+"' where foodid="+foodid);
}
}
controller层
package springmvc.less06.controller;
import java.io.OutputStream;
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 org.springframework.web.bind.annotation.ResponseBody;
import springmvc.less06.dao.MyFoodDaoImpl;
@Controller
public class MyFoodController {
//自动装配实现类
@Autowired
MyFoodDaoImpl mfi;
//根据名称查询
@RequestMapping(value="/queryFood",method=RequestMethod.GET)
public String quer(String foodname,OutputStream os)throws Exception{
//获取所有数据
List<Map<String,Object>> aur =mfi.selectFood(foodname);
//转换成json
JSONArray array= JSONArray.fromObject(aur);
String jst=array.toString();
//输出
os.write(jst.getBytes("UTF-8"));
return null;
}
/**
* 返回字节数组+@ResponseBody
* @param foodname
* @param os
* @return
* @throws Exception
*/
//根据菜名查询
@ResponseBody
@RequestMapping(value="/queryFoodre",method=RequestMethod.GET)
public byte[] querFood(String foodname,OutputStream os)throws Exception{
List<Map<String,Object>> aur =mfi.selectFood(foodname);
JSONArray array= JSONArray.fromObject(aur);
String jst=array.toString();
return jst.getBytes("UTF-8");
}
/**
* 直接返回对象Spring解析json
*
* @param foodname
* @return
* @throws Exception
*/
@RequestMapping(value="/queryFoodreturn",method=RequestMethod.GET)
public List<Map<String,Object>> querFoode(String foodname)throws Exception{
List<Map<String,Object>> aur =mfi.selectFood(foodname);
return aur;
}
//根据id删除
@RequestMapping(value="/food/{foodid}",method={RequestMethod.DELETE})
public String deleteFood(@PathVariable String foodid,OutputStream os) throws Exception{
try{
mfi.deleteFood(foodid);
os.write("1".getBytes("UTF-8"));
}catch(Exception e){
os.write("0".getBytes("UTF-8"));
}
return null;
}
//修改
@RequestMapping(value="/food/{foodId}",method={RequestMethod.PUT})
public String updateFood(@PathVariable String foodId,String foodname,String price,OutputStream os) throws Exception{
try {
mfi.updateFood(foodId, foodname, price);
os.write("1".getBytes("UTF-8"));
} catch (Exception e) {
os.write("0".getBytes("UTF-8"));
}
return null;
}
//新增
@RequestMapping(value="/food",method={RequestMethod.POST})
public String saveFood(String foodname,String price,OutputStream os) throws Exception{
try{
mfi.saveFood(foodname, price);
os.write("1".getBytes("UTF-8"));
}catch(Exception e){
os.write("0".getBytes("UTF-8"));
}
return null;
}
}
视图层
<%@ 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">
/*
封装的发送ajax的函数
*url 发送请求的地址
*方法类型 get或者post
*参数 通过 键=值&键=值 方式
*回调函数 当结果返回后 自动调用的函数 第一个参数就是返回的结果
function(responseText){
具体的逻辑(页面渲染)
}
*/
/*
使用ajax
尽量使用 true 异步模式 (防假死)
尽量将获取数据之后的逻辑处理(页面渲染)放在回调函数中
*/
function sendAjax(url,methodType,param,retnFunction){
//无刷新调用 http://localhost:8080/s/queryFood 获取到数据 数据通过dom方式添加到 table中
//ajax(异步的ajax)+json
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) {
//返回的json
retnFunction(xmlhttp.responseText)
}
}
if(methodType=="get" || methodType=="GET" ){
//open方法表示产生一个请求的关联(Get 提交)
xmlhttp.open("GET", url+"?"+param, true);
//提交
xmlhttp.send();
}else{
/**一个AJAX线程是否执行完成可以通过回调函数xmlhttp.onreadystatechange 是否执行完成来判断
异步 多个线程同事执行 无法判断谁先执行 true
同步 一次只允许一个线程执行 false 页面会假死
*/
xmlhttp.open("POST", url, true);
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}/queryFood","GET","foodname="+foodname,function(responseText){
//返回的是字符串的json
var resutlJson = responseText;
var resultObj=JSON.parse(resutlJson);
//获取表格对象
var table=document.getElementById("myTable");
//将所有名字为 dataTr的tr全部删除
var allDataTr=document.getElementsByName("dataTr");
var length=allDataTr.length;
for(var i=0;i<length;i++){
table.removeChild(allDataTr[0]);
}
//根据json的行数追加多个tr
for(var i=0;i<resultObj.length;i++){
var obj=resultObj[i];
var td=document.createElement("td");
td.innerText=obj.foodname;
var td1=document.createElement("td");
td1.innerText=obj.price;
var td2=document.createElement("td");
//删除按钮
var ib=document.createElement("button");
ib.innerText="X";
//
var ib1=document.createElement("button");
ib1.innerText="U";
td2.appendChild(ib);
td2.appendChild(ib1);
var tr=document.createElement("tr");
//将当前行的json对象绑定到当前按钮上
ib.foodObj=obj;
//将当前行的tr绑定到当前按钮上
ib.myLineTr=tr;
//删除按钮事件
ib.addEventListener("click",function(){
//获取当前按钮
var eventSrc=event.srcElement;
//删除当前行 + 发送ajax请求到后台 删除数据库
table.removeChild(eventSrc.myLineTr);
sendAjax("${pageContext.request.contextPath}/food/"+ib.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.setAttribute("name","dataTr");
//追加到tr
tr.appendChild(td);
tr.appendChild(td1);
tr.appendChild(td2);
//追加到table
table.appendChild(tr);
}
})
}
/**
新增的方法
**/
function saveFood(){
var myFoodName=document.getElementsByName("myFoodName")[0].value;
var myFoodPrice=document.getElementsByName("myFoodPrice")[0].value;
sendAjax("${pageContext.request.contextPath}/food","POST","foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
if(responseText==1){
document.getElementById('addDiv').style.display='none';
query();
alert("新增成功");
}else{
alert("新增失败");
}
});
}
/**
修改的方法
**/
function updateFood(){
var myFoodName=document.getElementsByName("umyFoodName")[0].value;
var myFoodPrice=document.getElementsByName("umyFoodPrice")[0].value;
var myFoodId=document.getElementsByName("umyFoodId")[0].value;
sendAjax("${pageContext.request.contextPath}/food/"+myFoodId,"POST","_method=put&foodName="+myFoodName+"&price="+myFoodPrice,function(responseText){
if(responseText==1){
document.getElementById('updateDiv').style.display='none';
query();
alert("修改成功");
}else{
alert("修改失败");
}
});
}
</script>
</head>
<body>
<input type='text' name="foodName" />
<input type='button' value="查询" οnclick="query()"><input type='button' value="新增" οnclick="document.getElementById('addDiv').style.display='block';">
<table id="myTable">
<tr><th>菜品名</th><th>菜品价格</th><th>操作</th></tr>
</table>
</body>
<div id="addDiv" style="display:none;position: absolute;left:40%;top:40%;z-index: 100;border:1px solid black; width:250px;height:100px ">
菜品名:<input type="text" name="myFoodName"><br/>
价 格:<input type="text" name="myFoodPrice"><br/>
<input type="button" value="保存" οnclick="saveFood()"> <input type="button" value="关闭" οnclick="document.getElementById('addDiv').style.display='none';" ><br/>
</div>
<div id="updateDiv" style="display:none;position: absolute;left:40%;top:40%;z-index: 100;border:1px solid black; width:250px;height:100px ">
<input type="hidden" name="umyFoodId" >
菜品名:<input type="text" name="umyFoodName"><br/>
价 格:<input type="text" name="umyFoodPrice"><br/>
<input type="button" value="修改" οnclick="updateFood()"> <input type="button" value="关闭" οnclick="document.getElementById('updateDiv').style.display='none';" ><br/>
</div>
</html>