Three ways to implement Ajax

Source: Internet
Author: User

This article is mainly compared with three ways to implement Ajax 1, Prototype.js 2, Jquery1.3.2.min.js 3, json2.js Java Code Collection Code spooler (Servlet), Access path Servlet/testajax:    Package ajax.servlet;  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;      /** * Ajax Example Spooler * @author Bing * @version 2011-07-07 * */public class Testajaxservlet extends HttpServlet { public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, Ioexcep          tion {response.setcontenttype ("text/html;charset=utf-8");                    PrintWriter out = Response.getwriter ();          String name = Request.getparameter ("name");                    String age = Request.getparameter ("Age");          System.out.println ("{\" name\ ": \" "+ name +" \ ", \" age\ ": \" "+ Age +" \ "}"); Out.print ("{\" name\ ": \" "+ Name +"\ ", \" age\ ":" + Age + "}");          Out.flush ();      Out.close (); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception,      IOException {doget (request,response); }} Testajaxservlet receives two parameters: Name and age, and returns a string written in JSON format. Front page parameter Input interface: Java code Collection Code <div id= "Show" > Display area </div> <div id= "Parameters" > Name:<input id= "name" n Ame= "Name" type= "text"/><br/> age:<input id= "age" name= "age" type= "text"/><br/> </div&gt  ; First, prototype implement Java code Collection code <script type= "Text/javascript" src= "prototype.js" ></script> <script type= "Te          Xt/javascript "> Function Prototypeajax () {var url =" Servlet/testajax ";//Request URL              var params = form.serialize ("parameters");//Submitted form var myajax = new Ajax.request (url,{     Method: "POST",//Request mode Parameters:params,//Parameter         Oncomplete:pressresponse,//Response function asynchronous:true});          $ ("show"). InnerHTML = "in process ..."; } function Pressresponse (request) {var obj = Request.responsetext;//Receive $ as text ("Show          "). InnerHTML = obj; var Objjson = Request.responseText.evalJSON ();            The received text is parsed into JSON format $ ("show"). InnerHTML + = "name=" + objjson[' name '] + "age=" + objjson[' age '); } </script> <input id= "Submit" type= "button" value= "Submit" onclick= "Prototypeajax ()"/><br/> in prototype Ajax implementation, use the Evaljson method to convert a string into a JSON object. Ii. jquery Implementation Java code Collection code <script type= "Text/javascript" src= "jquery-1.3.2.min.js" ></script> <script type  = "Text/javascript" src= "json2.js" ></script> <input id= "Submit" type= "button" value= "Submit"/><br/> <script type= "Text/javascript" > Function Jqueryajax () {var user={"name": "", "AG                 E ":" "}; User.Name= $ ("#name"). Val ();               user.age=$ ("#age"). Val ();                        var time = new Date (); $.ajax ({url: "servlet/testajax?time=" +time, Data: "Name=" +user.name+ "&age=" +user.age, datatype: "JSON",//The data type returned by the request page type: "GET", cont Enttype: "Application/json",//Note the Request page contenttype to be consistent here success:function (data) {//Here the data is the number returned by the request page According to var Datajson = json.parse (data);  Use the Parse method in Json2.js to convert data to JSON format $ ("#show"). HTML ("Data=" + Data + "name=" +datajson.name+ "age=" +                      Datajson.age); }, Error:function (XMLHttpRequest, Textstatus, Errorthrown) {$ ("#show"). HTML (                   "Error");             }                }); } $ ("#submit"). Bind ("click", Jqueryajax); Bind submit button </script> XMLHttpRequest implement Java code Collection code &LT;script type= "Text/javascript" > var xmlhttp;                 function Xmlhttprequestajax () {//Get data var name = document.getElementById ("name"). Value;            var = document.getElementById ("Age"). Value; Gets the XMLHttpRequest object if (window.             XMLHttpRequest) {xmlhttp = new XMLHttpRequest (); }else if (window. ActiveXObject) {var activxname = ["MSXML2.                 XMLHTTP "," Microsoft.XMLHTTP "]; for (var i = 0; i < activexname.length; i++) {try{xmlhttp = new ActiveXObject (acti                       Vexname[i]);                  Break  }catch (e) {}}} Xmlhttp.onreadystatechange = callback; The callback function var time = new Date ()//After the URL is added, so that each request is not the same as the var url = "Servlet/testajax?name=" +name+ "&               Amp;age= "+age+" &time= "+time; Xmlhttp.open ("GET", url,true);              Send request in Get mode Xmlhttp.send (NULL);                   The parameter is already in the URL, so there is no need to send it here} function callback () {if (xmlhttp.readystate = = 4) {   if (Xmlhttp.status = = 200) {//response succeeded var responsetext = Xmlhttp.responsetext;                    Receive response information as text var userdiv = document.getElementById ("show"); var Responsetextjson = Json.parse (responsetext);  Use the Parse method in Json2.js to convert data to JSON format Userdiv.innerhtml=responsetext + "Name=" + responsetextjson.name                + "age=" + responsetextjson.age; }}} </script> <input id= "Submit" type= "button" value= "Submit" onclick= "Xmlhttpreques   Tajax () "/><br/>

  

Three ways to implement Ajax

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.