Ajax实现无刷新图片点击浏览
ajax和servlet实现
1.用MySql建一张表
CREATE TABLE `photo` (
`id` int(6) NOT NULL auto_increment,
`photo_title` varchar(128) default NULL,
`photo_category_id` int(6) default NULL,
`photo_path` varchar(255) default NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=gbk;
2.主要js脚本
<
script type
=
"
text/javascript
"
>
var i = 1 ; // 设置点击次数,每次加1
// 创建XMLHttpRequest对象
function createXMLHttpRequest() ... {
var xmlhttpreq=false;
if(window.XMLHttpRequest)...{//mozilla
xmlhttpreq=new XMLHttpRequest();
}else if(window.ActiveXObject)...{//IE
try...{
xmlhttpreq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e)...{
try...{
xmlhttpreq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)...{}
}
}
return xmlhttpreq;//返回XMLHttpRequest对象
}
function getImgUrl() ... {
i++;
var xmlhttpreq=createXMLHttpRequest();//创建XMLHttpRequest对象
var handlerFunction=getReadyStateHandler(xmlhttpreq,updateImgUrl);//定义事件处理程序
xmlhttpreq.onreadystatechange=handlerFunction;//状态改变时触发事件
xmlhttpreq.open("POST","imgServlet.do",true);//请求URL
xmlhttpreq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpreq.send("photo_id="+i);//将参数传到服务器
}
// 定义时间处理程序
function getReadyStateHandler(xmlhttpreq,responseTextHandler) ... {
return function()...{//返回一个事件处理对象
if(xmlhttpreq.readyState==4)...{//请求完成
if(xmlhttpreq.status==200)...{//并且成功
responseTextHandler(xmlhttpreq.responseText);//处理从服务器返回的数据
}else...{
alert("HTTP错误:"+xmlhttpreq.status);
}
}
};
}
// 处理从服务器返回的数据
function updateImgUrl(imgUrl) ... {
document.getElementById("picture").src=imgUrl;//设置图片路径
}
var i = 1 ; // 设置点击次数,每次加1
// 创建XMLHttpRequest对象
function createXMLHttpRequest() ... {
var xmlhttpreq=false;
if(window.XMLHttpRequest)...{//mozilla
xmlhttpreq=new XMLHttpRequest();
}else if(window.ActiveXObject)...{//IE
try...{
xmlhttpreq=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e)...{
try...{
xmlhttpreq=new ActiveXObject("Microsoft.XMLHTTP");
}catch(e)...{}
}
}
return xmlhttpreq;//返回XMLHttpRequest对象
}
function getImgUrl() ... {
i++;
var xmlhttpreq=createXMLHttpRequest();//创建XMLHttpRequest对象
var handlerFunction=getReadyStateHandler(xmlhttpreq,updateImgUrl);//定义事件处理程序
xmlhttpreq.onreadystatechange=handlerFunction;//状态改变时触发事件
xmlhttpreq.open("POST","imgServlet.do",true);//请求URL
xmlhttpreq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttpreq.send("photo_id="+i);//将参数传到服务器
}
// 定义时间处理程序
function getReadyStateHandler(xmlhttpreq,responseTextHandler) ... {
return function()...{//返回一个事件处理对象
if(xmlhttpreq.readyState==4)...{//请求完成
if(xmlhttpreq.status==200)...{//并且成功
responseTextHandler(xmlhttpreq.responseText);//处理从服务器返回的数据
}else...{
alert("HTTP错误:"+xmlhttpreq.status);
}
}
};
}
// 处理从服务器返回的数据
function updateImgUrl(imgUrl) ... {
document.getElementById("picture").src=imgUrl;//设置图片路径
}
3.html
<
div
align
="center"
>
< img id ="picture" title ="请点击浏览下一幅图片" src ="images/01.jpg" onclick ="getImgUrl();" style ="cursor:hand;" />
</ div >
< img id ="picture" title ="请点击浏览下一幅图片" src ="images/01.jpg" onclick ="getImgUrl();" style ="cursor:hand;" />
</ div >
4servlet
import
java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImgServlet extends HttpServlet ... {
/** *//**
* Constructor of the object.
*/
public ImgServlet() ...{
super();
}
static...{
try ...{
Class.forName("com.mysql.jdbc.Driver");//加载驱动
} catch (ClassNotFoundException e) ...{
e.printStackTrace();
}
}
private Connection getCon()...{
try ...{
return DriverManager.getConnection("jdbc:mysql://localhost/test","root","njsan");
} catch (SQLException e) ...{
e.printStackTrace();
return null;
}
}
private int getRecordCount(String sql)...{
int count=0;
Connection conn=getCon();
PreparedStatement pstmt=null;
try ...{
pstmt=conn.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
if(rs.next())...{
rs.last();
count=rs.getInt("photo_category_id");
}
} catch (SQLException e) ...{
e.printStackTrace();
}
return count;
}
private String getImgUrl(int photo_category_id)...{
String imgUrl="";
int recourdCount=getRecordCount("select * from photo");
Connection conn=getCon();
PreparedStatement pstmt=null;
ResultSet rs=null;
try ...{
pstmt=conn.prepareStatement("select * from photo where photo_category_id=?");
if(photo_category_id%recourdCount==0)...{
pstmt.setInt(1,recourdCount);
}else...{
pstmt.setInt(1,photo_category_id%recourdCount);
}
rs=pstmt.executeQuery();
if(rs.next())...{
imgUrl=rs.getString("photo_path");
}
} catch (SQLException e) ...{
e.printStackTrace();
}finally...{
try ...{
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) ...{
e.printStackTrace();
}
return imgUrl;
}
}
/** *//**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
doPost(request,response);
}
/** *//**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
int photo_category_id=Integer.parseInt(request.getParameter("photo_id"));//获取参数
String imgUrl=getImgUrl(photo_category_id);
System.out.println(imgUrl);
response.getWriter().write(imgUrl);
}
}
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImgServlet extends HttpServlet ... {
/** *//**
* Constructor of the object.
*/
public ImgServlet() ...{
super();
}
static...{
try ...{
Class.forName("com.mysql.jdbc.Driver");//加载驱动
} catch (ClassNotFoundException e) ...{
e.printStackTrace();
}
}
private Connection getCon()...{
try ...{
return DriverManager.getConnection("jdbc:mysql://localhost/test","root","njsan");
} catch (SQLException e) ...{
e.printStackTrace();
return null;
}
}
private int getRecordCount(String sql)...{
int count=0;
Connection conn=getCon();
PreparedStatement pstmt=null;
try ...{
pstmt=conn.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
if(rs.next())...{
rs.last();
count=rs.getInt("photo_category_id");
}
} catch (SQLException e) ...{
e.printStackTrace();
}
return count;
}
private String getImgUrl(int photo_category_id)...{
String imgUrl="";
int recourdCount=getRecordCount("select * from photo");
Connection conn=getCon();
PreparedStatement pstmt=null;
ResultSet rs=null;
try ...{
pstmt=conn.prepareStatement("select * from photo where photo_category_id=?");
if(photo_category_id%recourdCount==0)...{
pstmt.setInt(1,recourdCount);
}else...{
pstmt.setInt(1,photo_category_id%recourdCount);
}
rs=pstmt.executeQuery();
if(rs.next())...{
imgUrl=rs.getString("photo_path");
}
} catch (SQLException e) ...{
e.printStackTrace();
}finally...{
try ...{
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) ...{
e.printStackTrace();
}
return imgUrl;
}
}
/** *//**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
doPost(request,response);
}
/** *//**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ...{
int photo_category_id=Integer.parseInt(request.getParameter("photo_id"));//获取参数
String imgUrl=getImgUrl(photo_category_id);
System.out.println(imgUrl);
response.getWriter().write(imgUrl);
}
}