Ajax实现无刷新图片点击浏览

本文介绍了一种使用Ajax和servlet实现的无刷新图片浏览功能。通过点击图片,客户端发送Ajax请求获取新的图片路径,并更新显示。服务器端通过查询数据库获取图片路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;//设置图片路径
           }

3.html

 

<div align="center">
        
<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);
    }





}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值