AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术。
AJAX 是一种用于创建快速动态网页的技术。
AJAX 不是新的编程语言,而是一种使用现有标准的新方法。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
传统的网页(不使用 AJAX)如果需要更新内容,必须重载整个网页页面。
使用ajax实现传输对象、集合、数组等(xml)
Jquery包中封装了ajax相关的
package com.maya.ajax; import java.io.IOException; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.maya.user.Users; /** * Servlet implementation class TestAjax2 */ @WebServlet("/testajax2") public class TestAjax2 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TestAjax2() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); Users user=new Users(); user.setName("张三"); user.setSex("男"); user.setAge(23); Users user1=new Users(); user1.setName("李四"); user1.setSex("女"); user1.setAge(24); Users user2=new Users(); user2.setName("王五"); user2.setSex("男"); user2.setAge(25); ArrayList<Users> list=new ArrayList<Users>(); list.add(user); list.add(user1); list.add(user2); response.getWriter().append("<?xml version='1.0' ?>"); response.getWriter().append("<users>"); for(Users u:list){ response.getWriter().append("<user>"); response.getWriter().append("<name>"+u.getName()+"</name>"); response.getWriter().append("<sex>"+u.getSex()+"</sex>"); response.getWriter().append("<age>"+u.getAge()+"</age>"); response.getWriter().append("</user>"); } response.getWriter().append("</users>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
HTML页面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="jquery-1.11.1.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#ss").click(function(){ $.ajax({ url:"testajax2", data:{}, type:"POST", dataType:"XML", success:function(httpdata){ var s=$(httpdata).find("user"); for(var i=0;i<s.length;i++){ $("#shuchu").append(s.eq(i).find("name").text()); $("#shuchu").append(" "); $("#shuchu").append(s.eq(i).find("sex").text()); $("#shuchu").append(" "); $("#shuchu").append(s.eq(i).find("age").text()); $("#shuchu").append("<br>"); } } }); }); }); </script> </head> <body> <span id="ss">点击获取数据</span> <div id="shuchu"></div> </body> </html>