业务需求:打开网站主页,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>