这里写链接内容## 写在前面 ##
真的好久没有更新博客了,面临毕业好多杂事要做,而且公司还要培训,真是忙的很。难得偷闲,今天就来谈一下ajax的分页吧!
首先我们来识别一下几个相关概念:
1、ajax:异步的javascript和xml 指的是在不刷新网页的情况下,可以和服务器端通信,局部刷新。
2、ajaj:其实这才是我们今天要用的,他的含义是: 异步的 javascript and json。
我们为什么要用这项技术呢?那是因为有些时候,需要数据的验证,但是,又不想整体的提交表单,所以,要进行局部提交。
1、首先要明白这个技术的核心就是xmlhttp。他是通过var xmlhttp=new XMLHttpRequest();得到的。
2、他有6个重要属性:
a. onreadystatechange属性 :它是用来处理服务器响应的函数。
b. states属性 : 响应的状态。
c. readyState属性: 请求的状态 共5种
状态 描述
0 请求未初始化(在调用open()之前)
1 请求已提出(调用send()之前)
2 请求已发送
3 请求处理中
4 请求已完成
d. responseText属性 :服务器响应返回的内容
e. open(“请求方式”,”请求地址”,永远为true);
f. send():如果是get请求 send(null)
如果是post请求 send(“请求参数”)
1.首先是login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
<script type="text/javascript">
function doblur(obj){
var tip = document.getElementById("tip");
var username=obj.value;
var xmlhttp;
try{
xmlhttp=new XMLHttpRequest();
}catch(ex){
alert("错了");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var text = xmlhttp.responseText;
if(text==1){
tip.innerHTML="可用"
}else{
tip.innerHTML="不可用"
}
}
};
xmlhttp.open("get","login?username="+username,true);
xmlhttp.send(null);
}
script>
head>
<body>
<form action="login" method="get">
用户名:<input type ="text" onblur="doblur(this)" name="username"/><label id ="tip">label><br>
密码:<input type ="text" name ="password"/><br>
<input type ="submit" value ="提交" id =""/><br>
form>
body>
html>
2.然后再看一下后台代码LoginAction.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String username=request.getParameter("username");
System.out.println(username);
if(username.startsWith("admin")){
out.print("1");
}else{
out.print("0");
}
}
3.get效果截图:
4.后台代码不变,前台jsp页面改成post请求。login.jsp代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
<script type="text/javascript">
function doblur(obj){
var tip = document.getElementById("tip");
var username=obj.value;
var xmlhttp;
try{
xmlhttp=new XMLHttpRequest();
}catch(ex){
alert("错了");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
var text = xmlhttp.responseText;
if(text==1){
tip.innerHTML="可用"
}else{
tip.innerHTML="不可用"
}
}
};
//xmlhttp.open("get","login?username="+username,true);
//xmlhttp.send(null);
xmlhttp.open("post","login",true);
//xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username="+username);
}
script>
head>
<body>
<form action="login" method="post">
用户名:<input type ="text" onblur="doblur(this)" name="username"/><label id ="tip">label><br>
密码:<input type ="text" name ="password"/><br>
<input type ="submit" value ="提交" id =""/><br>
form>
body>
html>
套路就这样,步骤操作也对,为什么会出错呢,简直没道理啊,不科学啊!找了半天终于找到了真相。原来后台识别post请求还是get请求是看请求头是什么,不能只改method,还要设置一下请求头。
6.真相
a.后台测试代码BackAction.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Enumeration<String> ens=request.getHeaderNames();
PrintWriter out=response.getWriter();
while (ens.hasMoreElements()) {
String name=ens.nextElement();
String value=request.getHeader(name);
out.println(name+"===="+value+"
");
}
}
从截图中我们可以清楚看到,post和get请求的主要区别在于请求头content-type,所以我们只要在post请求中设置一下请求头就可以了。还有一点要注意一下,请求头务必要设置在open()和send()方法之间,不然会没反应,亲测!务必谨记!
7.ajaj分页前台代码showdept.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'showdept.jsp' starting pagetitle>
<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">
<script type="text/javascript">
var tatalpage;
var spage;
//初始化
function doload() {
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest();//创建对象
} catch (e) {
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4&&xmlhttp.status==200) {//请求已完成且响应状态正确
var text = xmlhttp.responseText;//得到返回内容
var arr1 = eval(text);//将内容转换成表达式格式
totalpage = arr1[0].totalpage;
var arr = arr1[1].list;
var tb = document.getElementById("tb");
for ( var i = 0; i < arr.length; i++) {
var d = arr[i];
var tr = document.createElement("tr");
var td0 = document.createElement("td");
td0.innerHTML = d.deptno;
var td1 = document.createElement("td");
td1.innerHTML = d.dname;
var td2 = document.createElement("td");
td2.innerHTML = d.loc;
tr.appendChild(td0);
tr.appendChild(td1);
tr.appendChild(td2);
tb.appendChild(tr);
}
spage = document.getElementById("spage");
for ( var j = 1; j <= totalpage; j++) {
var option = document.createElement("option");
option.value = j;
option.innerHTML = j;
spage.appendChild(option);
}
}
}
xmlhttp.open("post", "showdept", true);
xmlhttp.setRequestHeader("content-type",
"application/x-www-form-urlencoded");//设置请求头
xmlhttp.send(null);
}
var pagenow = 1;
//实现分页
function doclick(obj) {
/* if (obj.value == "首页") {
pagenow = 1;
} else if (obj.value == "上一页") {
if(pagenow>1){
pagenow = Number(pagenow - 1);
}else{
pagenow=1;
}
} else if (obj.value == "下一页") {
if(pagenow
if (obj.innerHTML == "首页") {
pagenow = 1;
} else if (obj.innerHTML == "上一页") {
if(pagenow>1){
pagenow = Number(pagenow - 1);
}else{
pagenow=1;
}
} else if (obj.innerHTML == "下一页") {
if(pagenowNumber (pagenow + 1);
}else{
pagenow=totalpage;
}
} else if (obj.innerHTML == "尾页") {
pagenow = totalpage;
}else{
pagenow = Number(spage.value);//强制转换
}
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var text = xmlhttp.responseText;
var arr1 = eval(text);
totalpage = arr1[0].totalpage;
var arr = arr1[1].list;
var tb = document.getElementById("tb");
tb.innerHTML = "";//清空上一页的数据
for ( var i = 0; i < arr.length; i++) {
var d = arr[i];
var tr = document.createElement("tr");
var td0 = document.createElement("td");
td0.innerHTML = d.deptno;
var td1 = document.createElement("td");
td1.innerHTML = d.dname;
var td2 = document.createElement("td");
td2.innerHTML = d.loc;
tr.appendChild(td0);
tr.appendChild(td1);
tr.appendChild(td2);
tb.appendChild(tr);
}
for ( var i = 0; i < totalpage; i++) {
if (pagenow == spage.options[i].value) {
spage.options[i].selected = "selected";
}
}
}
}
xmlhttp.open("post", "showdept", true);
xmlhttp.setRequestHeader("content-type",
"application/x-www-form-urlencoded");//设置请求头
xmlhttp.send("pagenow=" + pagenow);
}
script>
head>
<body onload="doload()">
<center>
<h1>部门信息展示h1>
<table cellspacing="0" cellpadding="0" border="1" width="600">
<tr>
<td>部门编号td>
<td>部门名称td>
<td>部门地址td>
tr>
<tbody id="tb">
tbody>
<tr>
<td colspan="3">
<a href="javascript:void(0)" onclick="doclick(this)" >首页a>
<a href="javascript:void(0)" onclick="doclick(this)">上一页a>
<a href="javascript:void(0)" onclick="doclick(this)">下一页a>
<a href="javascript:void(0)" onclick="doclick(this)">尾页a>
<select id="spage" onchange="doclick(this)">
select>
td>
tr>
table>
center>
body>
html>
8.ajaj后台代码ShowDeptAction.java
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int pagesize=4;
int pagenow=1;
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String strpagenow = request.getParameter("pagenow");
if(strpagenow!=null){
pagenow= new Integer(strpagenow);
}
PrintWriter out = response.getWriter();
DeptDAO deptdao = new DeptDAO();
List list1;
try {
list1= deptdao.findByPage(pagesize, pagenow);
int count = deptdao.getCount();
int totalpage = (count-1)/pagesize+1;
JSONArray list = JSONArray.fromObject(list1);//将集合转成json格式
String arr ="[{\"totalpage\":"+totalpage+"},{\"list\":"+list.toString()+"}]";
out.print(arr);//务必在返回页面输出一下
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
小总结:做分页时我发现a标签没有value属性不过可以通过xxx.innerHTML获取到他的文字内容
好了,以上就是我近期对ajax的简单认知,希望对大家有所帮助,祝大家在编程这条路上越走越远!
点击下载源码