AJAX submit method (GET) Demon, ajax submit getdemon
AJAX, as an Asynchronous Javascript program execution method, greatly makes up for the shortcomings of the HTTP protocol (the HTTP protocol is stateless). You do not need to load the entire page, just load the required data, the XMLHttp object built in the browser has the open () method, which can be provided for asynchronous JS operations.
The following is a small example of a GET method. We recommend that you use POST when there are rare characters in a GET method that is large in data transmission compared with a POST method;
First, create a .html document with a random name. Enter:
<Body> <script type = "text/javascript" src = "1.js"> </script> User Registration: <br/> User ID: <input type = "text" name = "str1" id = "str1"/> <br/> User name: <input type = "text" name = "str2" id = "str2"/> <br/> <input type = "button" value = "register" onclick = "test (); "/> <p id =" mydiv "> </p> </body>
This is the code in the body, mainly a front-end interface. The <p> </P> below shows the returned values from the servlet.
Create a 1. js file with the following code:
Var xmlhttp = null;/*****/function test () {if (window. XMLHttpRequest) {xmlhttp = new XMLHttpRequest ();} else if (window. activeXObject) {xmlhttp = new ActiveXObject ("Micorsoft. XMLHTTP ");} else {alert (" failed to create object ");} str1 = document. getElementById ("str1 "). value; str2 = document. getElementById ("str2 "). value; xmlhttp. onreadystatechange = test2; xmlhttp. open ("GET", "servlet? Str1 = "+ str1 +" & str2 = "+ str2, true); xmlhttp. send (null);} function test2 () {if (xmlhttp. readyState = 4) {if (xmlhttp. status = 200) {var str3 = xmlhttp. responseText; document. getElementById ("mydiv "). innerHTML = str3 ;}} else {document. getElementById ("mydiv "). innerHTML = "wait patiently... ";}}
Configure the servlet code below, create a sevlet class, and write it in the doGet () method:
response.setContentType("text/html"); PrintWriter out = response.getWriter(); String str1 =new String(request.getParameter("str1").getBytes("ISO-8859-1"),"UTF-8"); String str2 =new String (request.getParameter("str2").getBytes("ISO-8859-1"),"UTF-8"); String responseText = "userNumber is:"+str1+",userName is:"+str2+"[Menthod is GET]"; out.println(responseText); out.close();
Simple servlet, doGet () method. After the servlet is created, the servlet ing (<url-pattern>/servlet </url-pattern>) labels are the same in web. xml.
Click "register.
Enter the following data and click "register:
You can see that there is no newly loaded page on the left side of the browser, and some data is directly updated through servlet. Typical examples of successful AJAX use are some page instant messaging such as Google earth.