Using JavaScript and jquery to simply implement AJAX technology

Source: Internet
Author: User

Definition of Ajax

Ajax is considered to be (asynchronous JavaScript and XML abbreviations). The technology that allows the browser to communicate with the server without having to refresh the current page is called Ajax.

How Ajax Works

The core of Ajax is the JavaScript object XMLHttpRequest. XMLHttpRequest allows you to use JavaScript to make requests to the server and handle the response without blocking the user.

First, using JavaScript to implement AJAX technology

1. First create a JSP page, import the JS page and create a new test button.

<Scripttype= "Text/javascript"src= "Ajaxget.js"></Script> <!--src Import the appropriate JavaScript to implement AJAX code -</Head><Body>    <inputtype= "button"ID= "BTN"value= "Ajax"/> <!--Test button -</Body>
2. Where we need to get the XMLHttpRequest object on the JS page, and we need to deal with compatibility issues
get XMLHttpRequest Objectfunctiongetxmlhttprequest () {varxmlhttpreq=NULL; if(Window. XMLHttpRequest) {//Mozilla BrowserXmlhttpreq =NewXMLHttpRequest (); }Else {        if(Window. ActiveXObject) {//IE Browser            Try{xmlhttpreq=NewActiveXObject ("Microsoft.XMLHTTP"); }            Catch(e) {Try{//IE BrowserXmlhttpreq =NewActiveXObject ("Msxml2.xmlhttp"); }                Catch(e) {} }}returnXmlhttpreq;
3. Then start writing the OnLoad event under the same page (get method send data)
Window.onload =function(){      varBtndom=document.getelementbyid ("BTN"); Btndom.onclick=function(){        //Ajax Steps        //1        varXHR =getxmlhttprequest (); //2. How the listening response determines that the request and response are correctXhr.onreadystatechange =function(){            if(Xhr.readystate = = 4) {//End of response                if(Xhr.status = = 200) {//Correct response                    //Receive response Data                    vardata =Xhr.responsetext;                alert (data);        }            }        }; //3. Open the connection        /** method:get or Post * URL: Request Path * Async:true (indicates async, default) False*/Xhr.open ("Get", "... /ajaxgetservlet?age=18&username=jack ",true); //4. Send DataXhr.send (NULL);//The data sent with the GET request send is NULL, and this step cannot be omitted    }; };
or use (the POST request//3rd 4th step is different)
Window.onload =function(){      varBtndom=document.getelementbyid ("BTN"); Btndom.onclick=function(){        //1        varXHR =getxmlhttprequest (); //2.Xhr.onreadystatechange =function(){            if(Xhr.readystate = = 4){                if(Xhr.status = = 200){                    vardata =Xhr.responsetext;                alert (data);        }            }        }; //3.Xhr.open ("Post", ".. /ajaxpostservlet ",true); /** 4. Send data * Send () string or null * String type is typically a key value pair "Username=zhangsan" * g The ET request is both send (NULL) * POST request to send data need to set the request header*/Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Xhr.send ("User=admin&age=12");  }; };
The URL of Step 3 requires that we create a servlet
 Public classAjaxgetservletextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {String age= Request.getparameter ("Age"); String UserName= Request.getparameter ("UserName"); System.out.println ( Age+"------"+userName); //Response DataResponse.getwriter (). Print ("Hello");//JS in step 2 listen to the response            }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

After the code is written, we just need to click the (value= "Ajax") test button to implement the asynchronous request and response using AJAX technology.

Second, using jquery to implement the Ajax technology case: How to use AJAX technology to achieve user registration when the user name is occupied? 1.jsp registration page
<Scripttype= "Text/javascript"src=".. /js/jquery-1.8.3.js "></Script><!--Importing jquery Packages -<Body>    <H3>jquery Implements Ajax</H3>    <P>User name:<inputID= "UserName"name= "UserName"/><spanID= "MSG"></span></P>    <Scripttype= "Text/javascript"src= "Jqdemo.js"></Script><!--jqdemo.js using jquery for Ajax -</Body>
2.js pages (no manual acquisition of XMLHttpRequest objects)
$(function(){    $("#userName"). Blur (function(){        varName = $ ( This). Val (); if(Name.trim () = = ""){            return; }        //jquery implements Ajax$.ajax ({URL:".. /jqueryusername ",//the requested pathType: "Post",//the request method defaults to getData: {//the data to be sent"Name": Name}, DataType:"Text",//types of response dataSuccessfunction(Result) {//Correct response                if(Result = = "Yes"){                    $("#msg"). HTML ("User name can be used"); }Else{                    $("#msg"). HTML ("User name is occupied"); }}, Error:function() {alert ("The request failed!" ");    }        }); });});
3.servlet page (get user name comparison is occupied)
 Public classJqueryusernameextendsHttpServlet { Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {System.out.println ("JQuery Ajax Authentication User name!" "); PrintWriter out=Response.getwriter (); String name= Request.getparameter ("name"); if("Ajax". Equals (name) | | "Admin". Equals (name) | | "Jack". Equals (name)) {            //user name is already in useOut.print ("No"); }Else{out.print ("Yes"); }    }     Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

Using JavaScript and jquery to simply implement AJAX technology

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.