之前在项目中使用ajax都是通过jQuery的Ajax API来进行的,今天试了一下通过基本的JavaScript来进行ajax请求,将代码记录下来:
jsp 页面
- <%@ page pageEncoding="UTF-8"%>
- >
- <html>
- <head>
- <title>Ajaxtitle>
- <script type="text/javascript" src="media/js/jquery.js" mce_src="media/js/jquery.js">script>
- <script type="text/javascript" src="media/ajax.js" mce_src="media/ajax.js">script>
- head>
- <body>
- Ajax.jsp<br/>
- <div id="msg" style="width:400px;height:200px;margin:1em;padding:1em;border:1px solid #DD6900">
- 啦啦啦
- div>
- <button id="start" style="margin:1em;border:1px solid #DD6900" mce_style="margin:1em;border:1px solid #DD6900">Start Ajaxbutton>
- body>
- html>
进行ajax请求的js 代码,可以附带一些json和xml数据(必须是post方法)
- var xmlHttp;
- function createXMLHttpRequest() {
- if (window.ActiveXObject) {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- else if (window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- }
- }
- var okFunc = function(){
- if(xmlHttp.readyState == 4) {
- if(xmlHttp.status == 200) {
- $("#msg").html(xmlHttp.responseText);
- }
- }
- }
- var startAjax = function(){
- $("#msg").html("Loading...");
- createXMLHttpRequest();
- if( !xmlHttp){
- return alert('create failed');
- }
- xmlHttp.open("POST", "Test", true);
- xmlHttp.onreadystatechange = okFunc;
- xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
- xmlHttp.send(document);
- }
- $(document).ready(function(){
- $("#start").click(startAjax);
- $.post("Test",{'name':'Hello','age':22});
- });
在服务器端的Servlet:
java 代码
- package ajax;
- import java.io.BufferedReader;
- 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 Test extends HttpServlet {
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- BufferedReader reader = request.getReader();
- String line = null;
- while((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- System.out.println("Start writing");
- response.setContentType("text/html");
- PrintWriter out = response.getWriter();
- out.println(");
- out.flush();
- out.close();
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- doGet(req, resp);
- }
- }