目录:
day01:AJAX
AJAX
1.1. Ajax 是什么 1
1.2. Ajax 解决了什么问题 1
1.3. Ajax 应用模型 2
2. Ajax 编程实现 2
2.4. Ajax 编程步骤 2
2.5. Ajax编程实现(了解) 3
2.5.1. 创建Ajax 请求对象 3
2.5.2. 初始化Ajax 请求 3
2.5.3. Ajax响应处理 4
2.6. Ajax 编程增强 4
2.6.4. Ajax 异步GET请求 4
2.6.5. Ajax 异步post请求 5
3. JQuery中的Ajax应用 6
3.7. ajax 函数应用 6
3.8. load函数应用 6
3.9. getJson函数应用 7
3.10. post 函数应用 7
3.1. 。。。。 8
4. 总结 8
4.2. 重点和难点分析 8
4.3. 常见FAQ 8
Ajax 概述
1.Ajax 是什么
Ajax 即
Asynchronous Javascript
And
XML
,是WEB应用程序开发的一种方法,它使用客户端脚本与web 服务器交互数据,并由最初的全局页面同步加载刷新升级为异步局部加载刷新方式动态刷新页面。
2.Ajax 解决了什么问题
-
页面加载性能问题(刷新整个页面快还是刷新局部页面快 ? )
-
用户体验问题(页面加载速度快了)
3.Ajax 应用模型
传统的web同步模型。
Ajax异步Web应用模型:(尽量减少客户端的阻塞)
2.Ajax 编程实现
4.Ajax 编程步骤
-
获取Ajax 请求对象(由浏览器端的Ajax引擎提供)
-
发送Ajax异步请求(发送到服务端)
-
获取Ajax异步数据(状态监听:状态码 4,200 )
-
局部刷新页面 (通过服务端返回的数据)
5.Ajax编程实现(了解)
1.创建Ajax 请求对象
function getRequestObject() {
if (window.XMLHttpRequest) {
// Opera, Safari, Mozilla, Chrome,Internet Explorer 7, and IE 8.
return (new XMLHttpRequest());
} else if (window.ActiveXObject) {
// Version for Internet Explorer 5.5 and 6
return (new ActiveXObject("Microsoft.XMLHTTP"));
} else {
//Fails on older and nonstandard browsers.
return (null);
}
}
1.初始化Ajax 请求
function sendRequest() {
var request = getRequestObject();
//Code to call when server responds
request.onreadystatechange =
function() { handleResponse(request) };
//URL of server-side resource,true is send request asynchronously
request.open("GET", "message-data.html", true);
//always null for get request
request.send(null);
}
3.Ajax响应处理
function handleResponse(request) {
// 4 means response from server is complete
if (request.readyState == 4 && request.status == 200) {
//alert(request.responseText);
htmlInsert(resultRegion, request.responseText);
}
}
function htmlInsert(id, htmlData) {
document.getElementById(id).innerHTML = htmlData;
}
6.Ajax 编程增强
4.Ajax 异步GET请求
function showTimeInCity(inputField, resultRegion) {
var baseAddress = "show-time-in-city";
var data = "city=" + getValue(inputField);
var address = baseAddress + "?" + data;
ajaxResult(address, resultRegion);
}
function ajaxResult(address, resultRegion) {
var request = getRequestObject();
request.onreadystatechange =
function() {
showResponseText(request,
resultRegion);
};
request.open("GET", address, true);
request.send(null);
}
function getValue(id) {
return (escape(document.getElementById(id).value));
}
function showResponseText(request, resultRegion) {
if ((request.readyState == 4) &&
(request.status == 200)) {
htmlInsert(resultRegion, request.responseText);
}
}
5.Ajax 异步post请求
function showTimeInCityPost(inputField, resultRegion) {
var address = "show-time-in-city";
var data = "city=" + getValue(inputField);
ajaxResultPost(address, data, resultRegion);
}
function ajaxResultPost(address, data, resultRegion) {
var request = getRequestObject();
request.onreadystatechange =
function() {
showResponseText(request,
resultRegion);
};
request.open("POST", address, true);
request.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
request.send(data);
}
function showResponseText(request, resultRegion) {
if ((request.readyState == 4) && (request.status == 200)) {
htmlInsert(resultRegion, request.responseText);
}
}
3.JQuery中的Ajax应用
7.ajax 函数应用
juqery 中的ajax函数用于向服务端发起一个异步的ajax请求.
例如:
$.ajax({ url: "address",
type:”GET”,
data: { param1: "foo bar", param2: "baz“ },
dataType: "json",
success: successHandlerFunction,
error: errorHandlerFunction,
cache: false,
})
Ajax 函数应用案例
$(function() {
$("#data-button-2").click(processAjaxRequest);
});
function processAjaxRequest () {
var params ={ param1: $("#field3").val(),param2: $("#field4").val() };
$.ajax({ url: "doFindPageObjects.do",
data: params,
success: function(result){
……..
} );
}
项目案例:
异步请求查询所有的blog,删除指定的数据信息
效果如图:
1、在项目到的Dao层写写对应功能的sql语句,在service层,和Controller层实现
在service层,
public interface BlogService {
List<Blog> findBlogs();
Blog findBlogById(Integer id);
int deleteBlogById(Integer id);
}
serviceImpl实现类
@Service
public class BlogServiceImpl implements BlogService{
@Autowired
private BlogDao blogDao;
private Logger log=
Logger.getLogger(getClass().getName());
public Blog findBlogById(Integer id) {
log.info("method start....");
//1.参数的合法性验证
if(id==null||id<1)
throw new RuntimeException("id 不合法");
//2.执行业务
Blog blog=blogDao.findBlogById(id);
System.out.println(blog.toString());
//3.返回结果
if(blog==null)
throw new RuntimeException("此博客已经不存在");
log.info("method end....");
return blog;
}
public List<Blog> findBlogs() {
log.info("method start....");
List<Blog> blogs=blogDao.findBlogs();
log.info("method end....");
return blogs;
}
@Override
public int deleteBlogById(Integer id) {
return blogDao.deleteBlogById(id);
}
}
和Controller层实现
@RequestMapping("blog03")
public ModelAndView blog03() {
ModelAndView mv = new ModelAndView();
mv.setViewName("blog03");
return mv;
}
@RequestMapping("findBlog03")
@ResponseBody
public List<Blog> findBlog03() {
List<Blog> list = bs.findBlogs();
return list;
}
@RequestMapping("deleteBlogById")
@ResponseBody
public String deleteBlogById(Integer id) {
bs.deleteBlogById(id);
return "delete ok";
}
创建jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>blog03</title>
</head>
<body>
<h1>异步请求查询所有的blog</h1>
<button onclick="findblogs()">查询所有</button>
<br />
<hr />
<table width="100%" height="40" cellpadding="1" cellspacing="0"
border="1">
<thead>
<tr>
<th>id</th>
<th>title</th>
<th>content</th>
<th>createdTime</th>
<th>authorId</th>
</tr>
</thead>
<tbody id="table_tbody">
</tbody>
</table>
<script type="text/javascript"
src="<%=request.getContextPath()%>/jquery/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//注册事件
$("#table_tbody").on("click", ".btn_delete", doDeleteBlog);
});
function doDeleteBlog() {
var deleteUrl = "deleteBlogById.do";
//获取button对象的父对象tr上绑定的id值
//data函数两个参数是绑定,一个参数是根据key获取绑定的值。
var id = $(this).parents("tr").data("id");
//难点id值的获取
var params = {
"id" : id
};
$.ajax({
url : deleteUrl,
data : params,
type : "post",
success : function(result) {
alert(result);
//刷新重新查询
findblogs();
}
});
}
function findblogs() {
alert("进入到方法了")
$.ajax({
url : "findBlog03.do",
type : "get",
dataType : "json",
success : function(result) {
console.log(result);
setTableBodyRows(result);
}
});
}
function setTableBodyRows(result) {
//1.获取tbody对象,并清空数据。
var tbody = $("#table_tbody");
tbody.empty();
//2.迭代数据,创建tr,并将数据添加到tr中
for ( var i in result) {
//循环一次获取一行记录
//创建tr对象
var tr = $("<tr></tr>");
//绑定数据(例如在删除操作中可能要用这个id值)
tr.data("id", result[i].id);
//创建多个td,并填充数据
var td = $("<td>" + result[i].id + "</td>" + "<td>"
+ result[i].title + "</td>" + "<td>"
+ result[i].content + "</td>" + "<td>"
+ result[i].createdTime + "</td>" + "<td>"
+ result[i].authorId + "</td>"
+ "<td><button class='btn_delete'>delete</button></td>");
//将td追加到tr对象中
tr.append(td);
//将每个tr追加到tbody中
tbody.append(tr);
}
}
</script>
</body>
</html>
8.load函数应用
jquery 中的load函数一般用于在某个位置异步加载某个
url页面,
语法
:load(url,[data],[callback])
其中:
-
url 表示远程一个地址
-
data 表示要传递数据( key/value )
-
callback 表示一个回调函数
例如:
案例1
$("#time-result-1").load("listUI.do");
例如
:
案例2
$("body").load("listUI.do",{color:red},function(){
…..
});
9.getJson函数应用
Jquery中的getJSON函数用于向服务端发起Ajax
GET
请求
获取json格式的数据
语法:
$.getJSON("url",[data], [callback])
例如
:
$.getJSON(“doFindPageObjects.do”,{pageCurrent:1},function(result){
//处理返回结果
})
10.post 函数应用
POST
方法为Jquery中的发送Ajax post请求的一种方法.
语法
:
post(url,[data],[callback])
例如:
$.post("doFindPageObjects.do",{pageCurrent:1},function(result){
…..
})