Native JavaScript (ES5) implements Ajax (can be used directly) and details __ Database

Source: Internet
Author: User
Tags browser cache

The

JavaScript code is as follows, as explained in comments:

var ajax = function (parameters) {/* * @description fetch data with Ajax. * @parameter {Object} Parameters data objects, properties are as follows: * @property {string} URL request Address * @property {string} [method] request, default " The data sent by the ' * @property {object} [data], the default ' {} ' * @property {Boolean} [Async] is asynchronous, default ' false ' * @property {fun Ction} [Success] request data success callback function, default "function (data) {}", "Data" indicates the request to @property {function} [ERROR] request data failed callback function, default "Functi On (status) {} ", status" indicates XHR's status code * @return {undefined} */var URL = parameters.url, method = Paramet Ers.method | | "Get", data = Parameters.data | | {}, async = Parameters.async | | False, Success = Parameters.success | | function (data) {}, error = Parameters.error | |
                function (status) {}, Isemptyobject = function (obj) {//Determine if NULL object for (var prop in obj) {
            return false;
        return true; }, FormData = function (data) {//format, the data object ' dATA "converted to" name=value&name2=value2 "form var newdata =" ";    For (var prop in data) {NewData + = encodeURIComponent (prop);
                Encode NewData + = "=" For attributes and (below) values.
                NewData + + encodeuricomponent (Data[prop]);
            NewData = "&";
        Return newdata.substring (0, newdata.length-1);

    };
    if (typeof url!== "string") {throw new Error ("URL must be a string");
    } if (typeof data!== "Object") {throw new Error ("Data must be a object"); } if (!isemptyobject (data)) {/////If the current data is not empty in the way of if (method = = = "Get") {//' get ', through "URL", so that the data inside the "information" parsing and formatting After "url" to go to if (Url.indexof ("?") = = 1) {//If there is no in the URL. ", avoid repeating" after URL ". "url ="? ";}
                else if (Url.indexof ("&")!== url.length-1) {//If the last character in the URL is not ' & ', avoid ' url ' to repeatedly add ' & ' where the data string is spliced
            URL + "&"; } URL += FormData (data);
        data = null; The else{//Post method is passed by the following "Xhr.send" method, but the data format of the argument is the same as the data format of "get", except that "post" is by placing the data in the "Request Body"
        It is passed to the backstage of data = FormData (data); } var xhr = new XMLHttpRequest (); Create a "XHR" object. ie7+ Xhr.onreadystatechange = function () {if (xhr.readystate = 4) {//request completed, and response is ready if (Xhr.sta Tus >= && xhr.status < 300) | | Xhr.status = = 304) {//Data request succeeded.  "2**" indicates a successful request, and "304" means to fetch the data from the browser cache success (Xhr.responsetext);  "Xhr.responsetext" indicates the requested data} else{error (Xhr.status);
    "Xhr.status" indicates that the request failed is the corresponding HTTP status code}};   Xhr.open (method, URL, async);  The parameters are: request mode, address, asynchronous Xhr.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); Sets the data format that sent the previous data format as form, and uses xhr.send (data) in the "post" mode; Send data. In "Get" mode, through the "URL" argument, you can not send the data here, but the parameter must be "NULL" and cannot be empty, but through the "post" method you need to pass the parameter;

Use examples:

Ajax ({
    URL: "test.php",
    data: {
        "id": 1,
        "name": "Xiao?) "Ming",
        "age": [
    }, Method
    : ' Get ',
    Async:false,
    success:function (data) {
        Console.log (data );
    },
    error:function (status) {
        console.log (status);
    }
);

test.php:

<?php
    $id = $_get["id"];
    $name = $_get["name"];
    $age = $_get["Age"];  $id = $_post["id"];  $name = $_post["name"];  $age = $_post["Age"];

    echo $id;
    echo $name;
    echo $age;
? >
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.