1. Introduction to Ajax
Ajax is considered to be the abbreviation of (Asynchronous JavaScript and XML), and the technology that allows the browser to communicate with the server without refreshing the current page is called Ajax.
eg: Baidu search, real-time map, etc. In the Ajax model, data is transmitted independently between the client and the server. The server can update the data without refreshing the entire page;
2. Ajax working principle diagram
3. The corresponding methods of sending and receiving Ajax
1. The corresponding method for sending a request
1) onreadystatechange event handling function: This function is triggered by the server rather than the user. Each time the readyState property changes, the onreadystatechange event will be triggered.
2) open(method,url,asynchronized): The open() of the XMLHttpRequest object allows the program to send requests with an Ajax call server. The method request type can be "GET" or "POST", and the url is a path string. Sysnchronized indicates whether the request is to be transmitted asynchronously.
3) send(data): data is a string that will also be passed to the server. If the "GET" request is selected, data is null.
2. Receive the corresponding method
1) readyState: represents the current state of Ajax, represented by a numeric value, 0 represents initialization, 1 represents loading, 2 represents loading, 3 represents the server is sending a response, 4 represents the response has been sent, and when the request is completed, each browser will set the value of readyState to 4;
2) status: Like in javaweb, 404 did not find the page, 403 prohibits access, 500 internal server error, 200 everything is normal, 304 has not been modified, in the XMLHttpRequest object, the status code sent by the server is saved in the status attribute. Through this value, we can ensure that the server has sent a successful response;
3) responseText: Contains the data sent from the server, which is generally HTML, XML or ordinary text. When the value of readyState is 4 and status is 200, the responseText attribute can only be used. On the surface, the Ajax request has ended. If the server returns XML, the data will be stored in responseXML.
4. Code demonstration (imitate Baidu search box)
1. Create a javaweb project (the project directory structure is as follows)
2. SearchServlet.java
package cn.jon.ajax; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import cn.jon.ajax.data.DataUtils; public class SearchServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set the output format of the request and response to utf-8 request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String keyword=request.getParameter("keyword"); if(keyword!=null) { DataUtils dataResource=new DataUtils(); List<String> list=dataResource.findDataList(keyword); //System.out.println(JSONArray.fromObject(list).toString()); response.getWriter().write(JSONArray.fromObject(list).toString()); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } } 3. DataUtils.java, read data under resource file
package cn.jon.ajax.data; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class DataUtils { private static List<String> dataList=new ArrayList<String>(); public static final String URL="/test.txt"; static { readResource(URL); // dataList.add("aa"); // dataList.add("ajax"); // dataList.add("afinal"); // dataList.add("bb"); }// public static void readResource(String url) { InputStream is=null; InputStreamReader isr=null; BufferedReader br=null; String line=null; try { is=DataUtils.class.getClassLoader().getResourceAsStream(url); isr=new InputStreamReader(is); br=new BufferedReader(isr); line=br.readLine(); while (null!=line) { if (!line.isEmpty()) { dataList.add(line); } line=br.readLine(); }//while } catch (IOException e) { e.printStackTrace(); } finally { if (null!=br) { try { br.close(); } catch (IOException e) { } } if (null!=isr) { try { isr.close(); } catch (IOException e) { } } if (null!=is) { try { is.close(); } catch (IOException e) { } } } } public List<String> findDataList(String str) { List<String> data=new ArrayList<String>(); for(String sData:dataList) { if (sData.contains(str)) { data.add(sData); } }//for return data; } } 4. index.jsp, page display
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <html> <head> <link rel="stylesheet" href="css/my.css"> <script type="text/javascript" src="js/my.js"> </script> </head> <body> <div id="mydiv"> <img src="img/baidu.png" > <!-- Input box--> <input type="text" size="50" id="keyword" onkeyup="getMoreContents()" onblur="keywordBlur()" onfocus="getMoreContents()"/> <input id="button" type="button" value="Baidu"/> <!-- The following is the content display area--> <div id="popDiv"> <table id="content-table" bgcolor="#FFFAFA" cellpacing="0" cellpadding="0"> <tbody id="content_table_body"> <!-- The data that is dynamically queried is displayed here--> </tbody> </table> </div> </body> </html>
5. My.js, the core part of ajax
var xmlHttp; //1. Function function to obtain the associated information of the user input content function getMoreContents(){ //First get the user input var content = document.getElementById("keyword"); if(content.value == ""){ //When the input box is empty, clear the previous data clearContent(); return; } //alert(content.value); //2. Then you want to send the user input content to the server, because we use ajax to send data asynchronously, so we need to use xmlHttp object//xmlHttp = get xmlHttp object; xmlHttp = createXMLHttp(); //alert(xmlHttp); //3. To send data to the server, first define the address of a server, var url = "search?keyword="+escape(content.value); //true means that the JavaScript script will continue to be executed after the send() method, without waiting for a response from the server. xmlHttp.open("GET",url,true); //xmlHttp binds a callback method. This callback method will be called when the xmlHttp state changes //xmlHttp state: 0-4, we only care about 4 (complete), so it is only meaningful to call the callback function after completion. xmlHttp.onreadystatechange = callback; //The parameters are already in the url, so you don't need to add the parameter xmlHttp.send(null); } //Get xmlHttp object function createXMLHttp(){ //Var xmlHttp that is suitable for most browsers; if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); } //Consider the browser compatibility if(window.ActiveXObject){ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //If the browser has ActiveXObject object, but does not have Microsoft.XMLHTTP parameter if(!xmlHttp){ xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } } return xmlHttp; } //Callback function function callback(){ //4 means completion if(xmlHttp.readyState == 4){ //200 means successful server response, 404 means not found, 500 means internal error of server if(xmlHttp.status == 200){ //The interaction is successful, and the corresponding data is obtained, which is in text format. var result = xmlHttp.responseText; //Analysis of the obtained data var json = eval("("+result+")"); //After obtaining these data, you can display the data dynamically. Display these data below the input box. //alert(json); setContent(json); } } } //Set the display of associated data. The parameters represent the associated data function setContent(contents){ //Clear the previous data clearContent(); //Set the position setLocaltion(); //First get the length of the associated data to determine how many <tr></tr> var size = contents.length; //Set the content for(var i =0;i < size;i++){ var nextNode = contents[i];//Represents the i-th element of json data var tr = document.createElement("tr"); var td = document.createElement("td"); td.setAttribute("borde","0"); td.setAttribute("gbcolor","#FFFAFA"); //Bind two styles for td (events when the mouse enters and moves out) td.onmouseover = function(){ this.className = 'mouseOver'; }; td.onmouseout = function(){ this.className = 'mouseOut'; }; td.onclick = function(){ //This method implements that when a related data is clicked with the mouse, the associated data is automatically filled into the input box. }; td.onmousedown = function(){ //When the mouse clicks on an associated data, the data will be automatically added to the input box document.getElementById("keyword").value =this.innerText; }; //When the mouse is suspended on the associated data, it will be automatically added to the input box/* td.onmouseover = function(){ this.className = 'mouseOver'; if(td.innerText != null) document.getElementById("keyword").value =this.innerText; } */ //Create a text node var text = document.createTextNode(nextNode); td.appendChild(text); tr.appendChild(td); document.getElementById("content_table_body").appendChild(tr); } } //Clear the previous data function clearContent(){ var contentTableBody = document.getElementById("content_table_body"); var size = contentTableBody.childNodes.length; //When deleting, delete from bottom to top for(var i = size-1;i>=0;i--){ //Specify deletion of the i-th child node contentTableBody.removeChild(contentTableBody.childNodes[i]); } //Clear the outer border of the associated data var popDiv = document.getElementById("popDiv").style.border="none"; } //When the input box loses focus, clear the previous data function keywordBlur(){ clearContent(); } //Set the position of displaying the associated information function setLocaltion(){ //The display position of the associated information must be consistent with the input box var content = document.getElementById("keyword"); var width = content.offsetWidth;//The length of the input box var left = content["offsetLeft"];//The distance to the left border var top = content["offsetTop"]+content.offsetHeight;//The distance to the top (plus the height of the input box itself) //Get the div of the display data var popDiv = document.getElementById("popDiv"); popDiv.style.border = "gray 1px solid"; popDiv.style.left = left+"px"; popDiv.style.top = top+"px"; popDiv.style.width = width+"px"; popDiv.style.top = top+"px"; popDiv.style.width = width+"px"; document.getElementById("content-table").style.width = width+"px"; } 6. my.css, control style
#mydiv { position: absolute; left: 50%; top: 50%; margin-left: -200px; margin-top: -120px; } #button { background-color: #5566ee; } .mouseOver { background: #708090; color: #fffafa; } .mouseOut { background: #fffafa; color: #000000; }Note: This code comes from the study of MOOC.com and has made improvements myself. I hope those who are interested can communicate and learn together.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.