Java AJAX加载图片

本文介绍了一个简单的使用Ajax加载图片的例子,通过jQuery发起GET请求到后端控制器,而后端定义了处理Ajax请求的方法,但未实现具体逻辑。前端部分展示了如何在接收到数据后更新图片的src属性。

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

业务需求:打开网站主页,ajax直接加载相应图片

导入js:jquery-1.8.3.js

 

后台controller代码:这里定义controller主要是为了定义ajax中的url

package com.mvc.control;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
public class HomeController {
 

    @RequestMapping("index")

public String index(){
return "index";
}
   
    @RequestMapping(value="Ajax")
public void Ind(HttpServletResponse response)  {}
    
   
}

    前台index.jsp代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"  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" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.js"></script>  
<script type="text/javascript">  
    $(document).ready(function(){
    $(function() {  
       $.ajax({ 
                type : "get",
                url : "Ajax",
                data : {
              
                },  
                beforeSend : function(XMLHttpRequest) {  
                    //设置图片为可见  
                    $('#myimg').show();  
                },  

                success : function(data, textStatus) {  

                    $("#yuxiaoyu").attr("src","../***.jpg");         <!-- 前台的src:图片属性、后面的是图片的url -->
          },  
                complete : function(XMLHttpRequest, textStatus) { 
                }, 
                error : function() {
                alert("出现了一个未知错误");
                }
            });
    }); 
    });
    
</script>  
<title>Insert title here</title>  
</head>  
<body>  
<table>
<tr>
<img  id="yuxiaoyu">

</tr>
</table>

















<!-- <style type="text/css">   
#main {  
    margin: 0 auto;  
    width: 400px;  
}  
  
#container {  
    width: 400px;  
    height: 300px;  
    border: 1px dashed #666;  
    text-align: center;  
    line-height: 300px;  
    position: relative;  
}  
  
#myimg {  
    position: absolute;  
    left: 50%;  
    top: 50%;  
    margin-left: -100px;  
    margin-top: -100px;  
    display: none;  
}  
</style> 
 


 <div id="main">  
        <button id="myBut">Ajax获取数据</button>  
        <div id="container">  
            <img  id="myimg">
            <img  id="myimg1">  
       </div>  
    </div>  
-->
</body>  
</html>  

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值