1、jQuery的Ajax与Java交互带加载图片
1.1 html代码
<body> <div id="main"> <button id="myBut">Ajax获取数据</button> <div id="container"> <img src="./img/load.jpg" id="myimg"> </div> </div> </body>
1.2 style代码
<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>
1.3 Javascript代码
<script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(function() { $('#myBut').click(function() { $.ajax({ type : "get", url : "JqueryAjaxServlet", data : { age : 18, name : "zhang" }, beforeSend : function(XMLHttpRequest) { //设置图片为可见 $('#myimg').show(); }, success : function(data, textStatus) { //设置图片隐藏 $('#myimg').hide(); var ajaxResult = jQuery.parseJSON(data); var age = ajaxResult.age; var name = ajaxResult.name; var mydiv = $('#container'); mydiv.html("name:" + name + "," + "age:" + age); }, complete : function(XMLHttpRequest, textStatus) { }, error : function() { } }); }); }); </script>
1.4 JqueryAjaxServlet.java代码
public class JqueryAjaxServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 模拟网络延迟
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String age = request.getParameter("age");
String name = request.getParameter("name");
String personJSON = "{\"name" + "\":\"" + name + "\"," + "\"age"
+ "\":" + age + "}";
System.out.println(personJSON);
response.getWriter().write(personJSON);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
1.5 web.xml代码