AJAX.basic
阿新 • • 發佈:2017-05-31
lencod query function int urlencode 請求 adding document obj
之前在項目中使用ajax都是通過jQuery的Ajax API來進行的,今天試了一下通過基本的JavaScript來進行ajax請求,將代碼記錄下來:
jsp 頁面 [xhtml] view plain copy- <%@ 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>
- 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 代碼 [java] view plain copy- 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);
- }
- }
AJAX.basic