JavaScript Ajax and server communication

Source: Internet
Author: User

XMLHttpRequest Object

-Common methods-:

Open ("Method", "url", whether asynchronously defaults to true, "username", "password") set the URL of the target for the asynchronous request

Send (content); Content can be an instance of a DOM object, an input stream, a string, a null

setRequestHeader ("header", "value") sets the value for the requested HTTP header

Abort () Stop or discard the current asynchronous request

getResponseHeader ("Headerlabel") returns the specified HTTP header information as a string

getAllResponseHeaders () returns full HTTP header information as a string, including server, Date, Content-type, Content-length

-Common Properties-:

"onReadyStateChange" is used to specify the time processor that is triggered when the state changes. In Ajax, when each state changes, it triggers the time processor, usually invoking a JavaScript function

(Instantiate a good xmlhttprequest (non IE) object or ActiveX (IE) object) Http_request.onreadystatechange=getresult;

"ReadyState" gets the state of the request, the property has 5 property values 0-uninitialized 1-loading 2-loaded 3-Interactive in 4-Done

"ResponseText" gets the response of the server, expressed as a string

"Responsexml" gets the corresponding server, expressed as XML. This object can be parsed as a DOM object

"Status" returns the HTTP status code for the server, with a common state of 200-indicating success 202-indicating that the request was accepted but not yet successful 400-Bad request 404-File not found 500-Internal server error

"StatusText" returns text corresponding to the HTTP status code, such as OK or not fount (not found), etc.

---using AJAX with server---i

Click the Detect User Name button in the Index.jsp form, call the JS Checkuer method, and then communicate with the servlet via AJAX to detect whether the user exists and display the results on the page.

1. Writing index.jsp and JavaScript Ajax

<%@ 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" >
<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" >
<script type= "Text/javascript" >
function CheckUser (userName) {
if (username.value== "") {
Alert ("Please enter user name");
Username.focus ();
Return
}else{
Createrequest ("checheuserservlet?username=" +username.value);
}
}
function createrequest (URL) {//Access server
Http_request = false;
if (window. XMLHttpRequest) {//Non IE browser
Http_request = new XMLHttpRequest ();
}else if (Windows. ActiveXObject) {//ie browser
try{
Http_request = new ActiveXObject ("Msxml2.xmlhttp");
}catch (e) {
try{
Http_request = new ActiveXObject ("Microsoft.XMLHTTP");
}catch (e) {

}
}
}
if (!http_request) {
Alert ("Cannot create Xmlhttpreuqest object instance! ");
return false;
}
Http_request.onreadystatechange = getresult;//callback function
Http_request.open ("GET", url, True);//get-mode asynchronous request URL (servlet or JSP or other ...) )
Http_request.send (null);//Send parameter
Http_request.open (method, URL, async, username, password)
}
function GetResult () {//Processing server response
if (http_request.readystate==4) {//Request complete
if (http_request.status==200) {//Request succeeded
document.getElementById ("message"). InnerHTML = Http_request.responsetext;
document.getElementById ("message"). style.display= "Block";
document.getElementById ("Checkedname"). style.display= "None";
}else{
Alert ("The page you requested has errors");
}
}
}
</script>

<body>
<form name= "register" action= "" method= "get" >
<table cellpadding= "0" cellspacing= "0" style= "width:500px;height:200px;" >
<tr>
&LT;TD width= "30%" align= "right" > User name:</td>
&LT;TD width= "35%" ><input type= "text" name= "username" ></td>
&LT;TD width= "35%" >
<input type= "button" Name= "Checkedname" id= "Checkedname" value= "Check username" onclick= "checkUser (register.username);" Style= "Float:left;" >
<div id= "message" style= "FLOAT:LEFT; display:none;font-size:12px;font-family:sans-serif;line-height:20px; " ></div>
</td>
</tr>
<tr>
&LT;TD align= "Right" > Password:</td>
&LT;TD colspan= "2" ><input type= "password" name= "password" ></td>
</tr>
<tr>
&LT;TD align= "Right" > Confirm password:</td>
&LT;TD colspan= "2" ><input type= "password" name= "CONFIRMPWT" ></td>
</tr>
<tr>
&LT;TD align= "right" >E-mail:</td>
&LT;TD colspan= "2" ><input type= "text" name= "email" ></td>
</tr>
<tr>
&LT;TD colspan= "3" >
<input type= "Submit" name= "submit" value= "register" style= "margin-left:30%;" >
</td>
</tr>
</table>
</form>
</body>

2. Write Checkusersevlet, annotation configuration checkuserservlet.

Package com.smxy.lxz.servlet;

Import java.io.IOException;
Import Java.io.PrintWriter;
Import Java.util.Arrays;

Import javax.servlet.ServletException;
Import Javax.servlet.annotation.WebServlet;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

@WebServlet ("/checheuserservlet")
public class Checheuserservlet extends HttpServlet {

/**
*
*/
Private static final long serialversionuid = 1L;

/**
* Destruction of the servlet. <br>
*/
public void Destroy () {
Super.destroy (); Just puts "destroy" string in log
Put Your code here
}

/**
* The Doget method of the servlet. <br>
*
* This method was called when a form had its tag value m Ethod equals to get.
*
* @param request the request send by the client to the server
* @param response The response send by the S Erver to the client
* @throws servletexception If a error occurred
* @throws IOException If an error occurred
*/
public void doget (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {
string[] user = {"Li xiong", "Lxz", "Lixiongzi"};

Response.setcharacterencoding ("UTF-8");
PrintWriter out = Response.getwriter ();

String userName = new String (Request.getparameter ("UserName"). GetBytes ("Iso8859-1"), "UTF-8");
Arrays.sort (user);
int result = Arrays.binarysearch (user, userName);
if (result>=0) {
Out.write ("already exists! ");
}else{
Out.write ("can use! ");
}
Out.flush ();
Out.close ();
}

/**
* The DoPost method of the servlet. <br>
*
* This method was called when a form have its tag value Method equals to post.
*
* @param request the request send by the client to the server
* @param response The response send by the S Erver to the client
* @throws servletexception If a error occurred
* @throws IOException If an error occurred
*/
public void DoPost (HttpServletRequest request, httpservletresponse response)
throws Servletexception, IOException {

Response.setcontenttype ("text/html");
PrintWriter out = Response.getwriter ();
Out.println ("<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.01 transitional//en\" > ");
Out.println ("<HTML>");
Out.println ("Out.println ("<BODY>");
Out.print ("This is");
Out.print (This.getclass ());
Out.println (", using the POST method");
Out.println ("</BODY>");
Out.println ("</HTML>");
Out.flush ();
Out.close ();
}

/**
* Initialization of the servlet. <br>
*
* @throws Servletexception If an error occurs
*/
public void Init () throws Servletexception {
Put Your code here
}

}

Effect

JavaScript Ajax and server communication

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.