Ajax Learning (ii): AJAX packaging tools that mimic jquery

Source: Internet
Author: User

Through the previous section of learning, basic understanding of the use of Ajax,

However, this is cumbersome to use, which encapsulates Ajax as a method, and as an AJAX tool, the use of Ajax can be achieved by passing in the corresponding parameters.

Emulate the Ajax of jquery.

The following is the Ajax use of jquery, only need to pass in the corresponding parameters, you can implement Ajax

First step: Create an Ajax tool class:

functionCreatexmlrequst () {Try{        return NewXMLHttpRequest (); }Catch(e) {Try{            return NewActiveXObject ("Msxml2.xmlhttp"); }Catch(e) {Try{                return NewActiveXObject ("Microsoft.XMLHTTP"); }Catch(e) {alert ("Browser version not supported"); Throwe; }        }    }}functionAjax (option) {varxmlhttp=Createxmlrequst (); //Open Link    if(!option.method)//Default Get{Option.method= "GET"; }    if(option.asyn==NULL)//default is asynchronous processing{Option.asyn=true;        } xmlhttp.open (Option.method,option.url,option.asyn); //Post needs to set the request header    if(option.method== "POST") {Xmlhttp.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); }    //send request, plus request parameterxmlhttp.send (Option.params); //registering listeners for onReadyStateChange events for asynchronous objectsXmlhttp.onreadystatechange=function()    {        //double judgment, determine whether the status is 4, and the response status code is:        if(Xmlhttp.readystate==4 && xmlhttp.status==200)        {            vardata; if(!Option.type) {Data=Xmlhttp.responsetext; }Else if(option.type== "XML") {Data=Xmlhttp.responsexml; }Else if(option.type== "Text") {Data=Xmlhttp.responsetext; }Else if(option.type== "JSON"){                vartext=Xmlhttp.responsetext; Data=eval ("(" +text+ ")"); }            //Call callback functionoption.callback (data); }    }}

The second step: introduce the script in the JSP, and invoke the Ajax () method in the script to implement Ajax.

<%@ Page Language="Java"ContentType="text/html; Charset=utf-8"pageencoding="UTF-8"%><%@ taglib Prefix="C"URI="Http://java.sun.com/jsp/jstl/core" %><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd "><HTML><Head><Metahttp-equiv= "Content-type"content= "text/html; charset=utf-8"><!--address can be used in the following ways, you can also directly write Url<script type= "Text/javascript" src= "/ajaxdemo/ajax_lib/ajaxutils.js" ></script > Introducing Ajax tool Scripts    -<Scripttype= "Text/javascript"src= "<c:url value= '/ajax_lib/ajaxutils.js '/>" ></Script><Scripttype= "Text/javascript">window.onload=function(){    //executes after the document has been loaded    varbtn=document.getElementById ("btn"); Btn.onclick=function() { ajax({URL:"/ajaxdemo/jsonajax", type:"JSON", Callback:function(data) {document.getElementById ("H3"). InnerHTML=Data.name+","+Data.age+","+Data.sex;    }            }        ); }}</Script><title>Testing Ajax Tools</title></Head><Body><H3>Testing Ajax Tools</H3><ButtonID= "BTN">Click the test Ajax tool</Button><H3ID= "H3"></H3></Body></HTML>

Step three: Write the servlet for the AJAX call: Return the JSON string to the client

 Packagecom. Ajax;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.annotation.WebServlet;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;Importjavax.servlet.http.HttpServletResponse; @WebServlet ("/jsonajax") Public classJsonajaxextendsHttpServlet {Private Static Final LongSerialversionuid = 1L;  PublicJsonajax () {Super(); }    protected voidDoget (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {response.setcharacterencoding ("UTF-8"); Response.setcontenttype ("Text/html;charset=utf-8"); //returns data to the client, obtained by AjaxResponse.getwriter (). Print ("{\" name\ ": \" Zhang san \ ", \" age\ ": \" 32\ ", \" sex\ ": \" male \ "}"); }    protected voidDoPost (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {doget (request, response); }}

Operation Result:

Ajax Learning (ii): AJAX packaging tools that mimic jquery

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.