一、介紹javascript
AJAX = 異步 JavaScript 和 XML。
AJAX 是一種用於建立快速動態網頁的技術。
經過在後臺與服務器進行少許數據交換,AJAX 能夠使網頁實現異步更新。這意味着能夠在不從新加載整個網頁的狀況下,對網頁的某部分進行更新。
傳統的網頁(不使用 AJAX)若是須要更新內容,必需重載整個網頁面。
二、建立一個簡單的實例、因爲ajax爲數據交互技術、因此首先須要有一個被調用的後臺接口或是能夠遠程調用的接口、這裏咱們本身建立一個簡單的實例css
package myajax; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.liferay.portal.kernel.json.JSONObject; public class MyServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void init(){}; public void doGet(HttpServletRequest request, HttpServletResponse response) { this.doPost(request, response); }; public void doPost(HttpServletRequest request, HttpServletResponse response){ response.setContentType("text/html;utf-8"); response.setCharacterEncoding("utf-8"); String out = ""; String type = request.getParameter("type"); if("ajax".equals(type)){ out=myAjax(); } try { response.getWriter().write(out); response.getWriter().flush(); response.getWriter().close(); } catch (IOException e) { e.printStackTrace(); } } private String myAjax() { String str = "ajax調用小例子QAQ"; return str ; }; }
這裏提供了一個供調用的url :http://127.0.0.1:8080/we/myservlet?type=ajaxhtml
二、頁面ajaxjava
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> <script type="text/javascript"> function sentGet(){ //建立ajax對象 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"); } //發送請求 xmlhttp.open("GET","http://127.0.0.1:8080/we/myservlet?type=ajax",true); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readyState==4 && xmlhttp.status==200){ document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } }; </script> </head> <body> <button onclick="sentGet();" >發送AJAX請求</button> <div id="myDiv"></div> </body> </html>
這裏 、咱們發送ajax請求、並實現局部刷新! 到此整個ajax的簡單流程結束.ajax