JavaScript encapsulates Ajax tool functions and Ajax in jquery

Source: Internet
Author: User
Tags http post jquery library

encapsulate Ajax Tool functions
/** * itcast WEB * Created by ZHOUSG on 2016/5/24.*//** 1. Type of request: Get post * 2. Request address URL * 3. is asynchronous or synchronous async false true * 4. Format of the requested content ContentType * 5.  Data transmitted by the JSON object * * 6. Respond to successful handler function success functions * 7. Response Failed handler Error function * * These are dynamic parameter parameter objects options **//*encapsulates a function*/window.$= {};/*to affirm an AJAX approach*/$.ajax=function(options) {if(!options | |typeofOptions! = ' object '){        return false; }    /*type of request*/    varType = Options.type | | ' Get ';/*Default Get*/    /*Request Address*/    varurl = Options.url | | Location.pathname;/*the current address*/    /*is asynchronous or synchronous?*/    varAsync = (Options.async = = =false)?false:true;/*Default Async*/    /*format of request content*/    varContentType = Options.contenttype | | "Text/html"; /*data being transferred*/    vardata = Options.data | | {};/*{name: ', Age: '}*/    /*This format needs to be converted to NAME=XJJ at the time of submission.*/    varDatastr = ' '/*Data String*/     for(varKeyinchdata) {Datastr+ = key+ ' = ' +data[key]+ ' & '; } datastr= Datastr && Datastr.slice (0,-1); /*Ajax Programming*/    varXHR =NewXMLHttpRequest (); /*Request Line*/    /*(type== ' get '? url+ '? ') +datastr:url) Determine the current request type*/Xhr.open (Type, (type= = ' get '? url+ '? ' +Datastr:url), async); /*Request Header*/    if(Type = = ' Post ') {Xhr.setrequestheader (' Content-type ', ' application/x-www-form-urlencoded '); }    /*Request Body*/    /*request type needs to be judged*/xhr.send (Type= = ' Get '?NULL:d atastr); /*Monitoring Response Status change response status*/Xhr.onreadystatechange=function(){        /*Request response complete and successful*/        if(Xhr.readystate = = 4 && xhr.status = 200){            /*Success*/            vardata = '; varContentType = Xhr.getresponseheader (' Content-type ')); /*If our server returns an XML*/            if(Contenttype.indexof (' xml ') >-1) {Data=Xhr.responsexml; }            /*If our server returns a JSON string*/            Else if(Contenttype.indexof (' json ') >-1){                /*Convert JSON objects*/Data=Json.parse (Xhr.responsetext); }            /*Otherwise, he's a string.*/            Else{Data=Xhr.responsetext; }            /*callback Success Handler function*/options.success&&options.success (data); }        /*Timing Request Xhr.status Unsuccessful He also needs the response completed before it is considered a wrong request*/        Else if(Xhr.readystate = = 4){            /*Error*/Options.error&& options.error (' You request fail! ')); }}}$.post=function(options) {Options.type= ' Post '; $.ajax (options);} $.get=function(options) {Options.type= ' Get '; $.ajax (options);}
jQuery Ajax operation functions

The JQuery Library has a complete Ajax compatibility suite. The functions and methods allow us to load data from the server without refreshing the browser.

function Description
Jquery.ajax () Executes an asynchronous HTTP (Ajax) request.
. Ajaxcomplete () Registers the handler to invoke when the Ajax request is complete. This is an Ajax event.
. Ajaxerror () Registers the handler to invoke when the Ajax request is complete and an error occurs. This is an Ajax event.
. Ajaxsend () Displays a message before the Ajax request is sent.
Jquery.ajaxsetup () Sets the default value for future Ajax requests.
. Ajaxstart () Registers the handler to invoke when the first Ajax request finishes. This is an Ajax event.
. Ajaxstop () Registers the handler to invoke when all Ajax requests are completed. This is an Ajax event.
. Ajaxsuccess () Displays a message when the Ajax request completes successfully.
Jquery.get () Use an HTTP GET request to load data from the server.
Jquery.getjson () Loads JSON-encoded data from the server using an HTTP GET request.
Jquery.getscript () Use an HTTP GET request to load a JavaScript file from the server, and then execute the file.
. Load () Load the data from the server and put the matching elements back into the HTML.
Jquery.param () Creates a serialized representation of an array or object, suitable for use in URL query strings or Ajax requests.
Jquery.post () Load data from the server using an HTTP POST request.
. Serialize () Serializes the contents of the form into a string.
. Serializearray () Serializes the form element, returning the JSON data structure.
  • jquery provides us with a more powerful Ajax package
  • $.ajax ({}) configurable way to initiate AJAX requests
  • $.get () Initiate AJAX requests in Get mode
  • $.post () initiate an AJAX request by post
  • $ (' form '). Serialize () Serialize the form (that is, format key=val&key=val)
  • URL interface Address
  • Type Request method
  • Timeout Request timed out
  • DataType Server return format
  • Data to send requests
  • Beforesend:function () {} Call before request initiation
  • Success the call after a successful response
  • Error response when calling
  • The complete response is invoked (both success and failure)

JavaScript encapsulates Ajax tool functions and Ajax in jquery

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.