1、关于Ajax交互的步骤
1.1 获取到xmlhttprequest
1.2 设置xmlhttprequest的onreadystatechange响应事件
1.3 准备获取ajax请求 xmlhttp.open("GET", "AjaxServerlet?age=18&name=zhang", true); //Ajax方法的GET方式请求,参数是通过xmlhttp.open()携带的
1.4 发送ajax请求xmlhttp.send();
1.5 处理Ajax交互获取到的数据,具体的处理在xmlhttprequest的onreadystatechange响应事件中实现
2、Ajax与Java的Servlet交互的小例子
2.1 html代码
<body> <button id="mybtn">点击</button> <div id="myAjax"> </div> </body>
2.2 JavaScript代码
<script type="text/javascript"> //1、获取到xmlhttprequest function getXmlhttp() { var xmlhttp; if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp = new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } return xmlhttp; } window.onload = function() { document.getElementById('mybtn').onclick = function() { //1、获取到xmlhttprequest 对象 var xmlhttp = getXmlhttp(); //2、xmlhttprequest的响应事件 xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //5、操作获取到的信息 //5.1 ajax返回的数据,转换为javascript对象 // 5.1.1 利用eval实现转换 var ajaxResult = eval("(" + xmlhttp.responseText + ")"); //5.1.2 利用jquery的方法,对于jQuery.parseJSON(),键值必须为双引号 /* var ajaxResult = jQuery.parseJSON(xmlhttp.responseText); */ //5.2获取JavaScript对象的属性 var age = ajaxResult.age; var name = ajaxResult.name; //5.3获取到页面的DIV,并设置内容 var mydiv = document.getElementById("myAjax"); mydiv.innerHTML = "name:" + name + "," + "age:" + age; } } //3、准备获取ajax请求 //3.1 对于get请求,带参数的方式,直接在open函数的请求地址带上参数 xmlhttp.open("GET", "AjaxServerlet?age=18&name=zhang", true); //4、发送ajax请求 xmlhttp.send(); }; } </script>
2.3 style代码
<style type="text/css"> #myAjax { width: 400px; height: 400px; border: 1px dashed red; text-align: center; /* div中的文字水平方向居中显示 */ line-height: 400px; /*这个和div的高度相同,div中的文字就会垂直方向居中显示 */ font-size: 16px; font-weight: bold; } </style>
3、AjaxServerlet.java代码
public class AjaxServerlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String age = request.getParameter("age"); String name = request.getParameter("name"); Person person = new Person(name, age); 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); } }
4、web.xml 代码
<servlet> <servlet-name>AjaxServerlet</servlet-name> <servlet-class>com.ajax.com.AjaxServerlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AjaxServerlet</servlet-name> <url-pattern>/AjaxServerlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list>
时间: 2024-10-06 06:51:06