<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>ajax demo</title> <script type="text/javascript"> var xmlHttpRequest = null; function ajaxSubmit(){ // window.alert(window.ActiveXObject); if(window.ActiveXObject){ //是IE浏览器 xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){ //除IE外的其他浏览器 xmlHttpRequest = new XMLHttpRequest(); } /* 使用Ajax准备向服务器端发送一个请求 */ if(null != xmlHttpRequest){ //使用GET方式, //异步 var num1 = document.getElementById("num1").value; var num2 = document.getElementById("num2").value; // xmlHttpRequest.open("GET","AjaxServlet?num1=" + num1 + "&num2=" + num2,"true"); xmlHttpRequest.onreadystatechange = ajaxCallBack; //注册一个回调函数 //向服务器端发送数据 // xmlHttpRequest.send(null); //get方式设置为null //post方式 xmlHttpRequest.open("POST","AjaxServlet","true"); //使用post方式提交数据,必须加上下面这行代码 xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlHttpRequest.send("num1=" + num1 + "&num2=" + num2); } } function ajaxCallBack(){ if(xmlHttpRequest.readyState == 4){ if(xmlHttpRequest.status == 200){ var responseText = xmlHttpRequest.responseText; document.getElementById("content").innerHTML = responseText; } } } </script> </head> <body> <input type="text" name="num1" id="num1"/> <br/> <input type="text" name="num2" id="num2"/> <br/> <input type="button" value="从服务区端获取数据" onclick="ajaxSubmit();"/> <div id="content"></div> </body> </html>
后台处理代码
package com.ajax.test; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class AjaxServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { response.setContentType("text/html"); String num1 = request.getParameter("num1"); String num2 = request.getParameter("num2"); int num3 = Integer.valueOf(num1) + Integer.valueOf(num2); PrintWriter out = response.getWriter(); System.out.println("AjaxServlet.doGet()"); out.println(num3); } public void doPost(HttpServletRequest request,IOException { System.out.println("AjaxServlet.doPost()"); this.doGet(request,response); } }
原文链接:https://www.f2er.com/ajax/164964.html