In a Web page file, the following XMLHttpRequest object can be used to implement the asynchronous operation of Ajax
function Getvaluefromserver () {var xmlhttprequest = null; if (window.
ActiveXObject) {//If the XMLHttpRequest is implemented through Microsoft ActiveXObject = new ActiveXObject ("Microsoft.XMLHTTP"); else if (window.
XMLHttpRequest) {//If it is implemented through Firefox and Chrome.
XMLHttpRequest = new XMLHttpRequest (); } if (null!= XMLHttpRequest) {//Method True is in asynchronous mode, and false is sending get requests synchronously, "Myservlet" represents the relative URL of the request Xmlhttpreque
St.open ("Get", "addaction" + "? value1=" + value1 + "&value2=" + value2,true);
Xmlhttprequest.onreadystatechange = Ajaxcallback; /* If the request being sent is a get type, the parameter assignment null if a request parameter is added to "Myservlet" in Xmlhttprequest.open ("Get", "Myservlet", true), in the form of "Myservlet?"
Username=hello&password=world "If the parameter of the type of post is unloaded in the form of a name-value pair, the Send () method is Xmlhttprequest.send (null).
function Ajaxcallback () {if (xmlhttprequest.readystate = 4) {//http request is correct (200) if (Xmlhttprequest.status = = 200) {//The requested data format is plain text.
var responsetext = Xmlhttprequest.responsetext;
document.getElementById ("Div1"). InnerHTML = ResponseText; }
}
}
}
As for the server side can take the following code to cooperate (if use is struts2 words)
Servletresponse HttpServletResponse = Servletactioncontext.getresponse ();
PrintWriter printwriter = null;
Try
{
printwriter = Httpservletresponse.getwriter ();
}
catch (IOException e)
{
e.printstacktrace ();
}
A signal can be generated from the object of the PrintWriter class and passed back to the client. There is a xmlhttprequest.responsetext in the callback function defined in the previous JavaScript script segment; The indicator is a normal text format rather than an XML format and is not a JSON data format. And the value inside is the data returned by the PrintWriter object.
function Ajaxcallback ()
{
if (xmlhttprequest.readystate = 4)
{
HTTP request is correct (200)
if (Xmlhttprequest.status = 200)
{
The requested data format is plain text.
var responsetext = Xmlhttprequest.responsetext;
document.getElementById ("Div1"). InnerHTML = ResponseText;
}
}
}
If it's a servlet, it's straight.
PrintWriter printwriter = Resp.getwriter (); Res is a HttpServletRequest object