An example of how Ajax interacts with the servlet _java

Source: Internet
Author: User
Tags stmt mysql import stringbuffer

This article analyzes the interaction between Ajax and servlet in the form of an instance, and there are more detailed comments in the code to help you read and understand. The specific implementation methods are as follows:

1.JavaScript part

var req;
 /* Send parameters via asynchronous transmission XMLHTTP to Ajaxservlet, return the eligible XML document/var URL;
  function GetResult () {var F=document.getelementbyid ("Form_pub"); var Key=f.s.options[f.s.selectedindex].text; Gets a reference to the Chinese version of Select if window.
  XMLHttpRequest) {req = new XMLHttpRequest ();
 url = "ajaxservlet?action=" +key+ "&bm=utf-8"; }else if (window.
  ActiveXObject) {req = new ActiveXObject ("Microsoft.XMLHTTP");
 url = "ajaxservlet?action=" +key+ "&BM=GBK"; 
  } if (req) {Req.open ("get", url, True);
  Req.setrequestheader ("Content-type", "text/html;charset=utf-8"); 
  Here if not set the head will cause Firfox send data error, Servlet received by the parameters of garbled, in IE normal req.onreadystatechange = complete;
  Req.send (NULL); Req.setrequestheader ("Content-type", "text/xml; 
 Charset=utf-8 "); }/* Analysis returned XML document/function complete () {if (req.readystate = = 4) {if (Req.status =) {var items=document
  . getElementById ("Belong");
   The following is a parse-returned XML document var xmldoc = Req.responsexml; var node=xmldoc.getelementsbytagname ("Type_name");
    var str=new Array ();
    var str=null; Empty the work items.innerhtml= "";
     Deletes all contents in a Select for (Var i=0;i<node.length;i++) {Str=node[i];
     alert (Str.childnodes[0].nodevalue);
      var objectoption=document.createelement ("option");
     Items.options.add (objectoption); Firfox does not support innertext must replace the if window with Textcontent.
      ActiveXObject) {Objectoption.innertext=str.childnodes[0].nodevalue;}
    else {objectoption.textcontent=str.childnodes[0].nodevalue;}

 }
   }
  }
 }

2.servlet End:

Package Ajax;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;


Import data_getconn.getconn;//This package is written by yourself to get a reference to MySQL import java.sql.*;//This package must have!! public class Ajaxservlet extends httpservlet{//private static final String content_type = "text/xml; Charset=utf-8 "//Here it is best to unify the code with UTF-8 public void init () throws servletexception{} public void Doget (HttpServletRequest req Uest,httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("text/xml;
 Charset=utf-8 ");
  The following two sentences are cancelled in the local cache Response.setheader ("Cache-control", "No-cache");
 Response.setheader ("Pragma", "No-cache");
 PrintWriter out = Response.getwriter ();
 String action = request.getparameter ("action");
 
 String BM = Request.getparameter ("BM"); if (("GBK"). Equals (BM)) {action=new String (action.getbytes ("iso-8859-1"), "GBK ");//The data obtained will be GBK with the new code!
 (thank Dong Wei Teacher)} else {action=new String (action.getbytes ("iso-8859-1"), "GBK");
   try {getconn wq=new getconn ();
   Connection Con=wq.getcon ();
   Statement stmt=con.createstatement ();
   ResultSet rs=stmt.executequery ("Select items from class where main= '" +action+ "");
    StringBuffer sb = new StringBuffer ();
   Sb.append ("<type>");
     
   while (Rs.next ()) {sb.append ("<type_name>" +rs.getstring (1) + "</type_name>");
    }//sb.append ("<type_name>" +action+ "</type_name>"); 
    Sb.append ("</type>");
    Out.write (sb.tostring ())//Note the stream that is output to the JSP, the method of interception in script Out.close ();
    Stmt.close ();
  Con.close (); \ catch (Exception ex) {}}}
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.