1. 程式人生 > >AJAX.basic

AJAX.basic

lencod query function int urlencode 請求 adding document obj

之前在項目中使用ajax都是通過jQuery的Ajax API來進行的,今天試了一下通過基本的JavaScript來進行ajax請求,將代碼記錄下來:

jsp 頁面 [xhtml] view plain copy
  1. <%@ page pageEncoding="UTF-8"%>
  2. >
  3. <html>
  4. <head>
  5. <title>Ajaxtitle>
  6. <script type="text/javascript" src="media/js/jquery.js" mce_src="media/js/jquery.js">script>
  7. <script type="text/javascript" src="media/ajax.js" mce_src="media/ajax.js">script>
  8. head>
  9. <body>
  10. Ajax.jsp<br/>
  11. <div id="msg" style="width:400px;height:200px;margin:1em;padding:1em;border:1px solid #DD6900">
  12. 啦啦啦
  13. div>
  14. <button id="start" style="margin:1em;border:1px solid #DD6900" mce_style="margin:1em;border:1px solid #DD6900">Start Ajaxbutton>
  15. body>
  16. html>
進行ajax請求的js 代碼,可以附帶一些json和xml數據(必須是post方法) [javascript] view plain copy
  1. var xmlHttp;
  2. function createXMLHttpRequest() {
  3. if (window.ActiveXObject) {
  4. xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
  5. }
  6. else if (window.XMLHttpRequest) {
  7. xmlHttp = new XMLHttpRequest();
  8. }
  9. }
  10. var okFunc = function(){
  11. if(xmlHttp.readyState == 4) {
  12. if(xmlHttp.status == 200) {
  13. $("#msg").html(xmlHttp.responseText);
  14. }
  15. }
  16. }
  17. var startAjax = function(){
  18. $("#msg").html("Loading...");
  19. createXMLHttpRequest();
  20. if( !xmlHttp){
  21. return alert(‘create failed‘);
  22. }
  23. xmlHttp.open("POST", "Test", true);
  24. xmlHttp.onreadystatechange = okFunc;
  25. xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  26. xmlHttp.send(document);
  27. }
  28. $(document).ready(function(){
  29. $("#start").click(startAjax);
  30. $.post("Test",{‘name‘:‘Hello‘,‘age‘:22});
  31. });

在服務器端的Servlet:

java 代碼 [java] view plain copy
  1. package ajax;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.http.HttpServlet;
  7. import javax.servlet.http.HttpServletRequest;
  8. import javax.servlet.http.HttpServletResponse;
  9. public class Test extends HttpServlet {
  10. public void doGet(HttpServletRequest request, HttpServletResponse response)
  11. throws ServletException, IOException {
  12. BufferedReader reader = request.getReader();
  13. String line = null;
  14. while((line = reader.readLine()) != null) {
  15. System.out.println(line);
  16. }
  17. System.out.println("Start writing");
  18. response.setContentType("text/html");
  19. PrintWriter out = response.getWriter();
  20. out.println(");
  21. out.flush();
  22. out.close();
  23. }
  24. @Override
  25. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  26. throws ServletException, IOException {
  27. doGet(req, resp);
  28. }
  29. }

AJAX.basic