[make wheel] manual package AJAX - basic version

Keywords: Javascript JSON IE

I believe that AJAX has been used, and there must be a lot of self-made packages, but they should be simple to request, not to set the synchronous, asynchronous and returned data formats

  • Compatible with IE5 and IE6
  • You can use get and post to request data
  • You can set the request header with the required ideas and syntax. You need to expand it by yourself
  • Return data format can be set, not set as default
  • I didn't write the data splicing of get request. I can add it if necessary
  • There will be encapsulation of ES6 syntax later. Please wait
  • Note: the code uses ES5 syntax. The parameters of this version I write can only be passed in order

Direct code

//1. Write ajax with ES5
var ajax = function (url,method,data,async,success,error,resType) {
    //Set variable defaults
    method = method || "GET";
    async = async || true;
    data = data || "";
    resType = resType || "";
    //data verification
    if(!url || url === ''){
        throw new Error('url Can not be empty');//Throw is used to throw an exception 
    if(method==="GET" && data != ""){
        throw new Error('Please send get Request parameters are written in url in');//Because the time is not enough, we will not write parameter splicing anymore. Interested partners can add parameter splicing function by themselves
    //Convert all lowercase to uppercase
    method = method.toUpperCase();
    //Determine whether it is a lower version IE
    if (window.XMLHttpRequest) { //Whether xmlhttprequse is supported
        var xhr = new XMLHttpRequest();
    } else { //Low version IE 
        var xhr = new ActiveXObject("Microsft.XMLHTTP");
    //Whether the request address of xmlhttp.open(method,url,async) request type is asynchronous
    xhr.open(method, url, async);
    //Set request header
    //Determine whether to set
    //Loop headers set request headers
    // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    //Format return data
    if(async){//If synchronization is set, return data format cannot be set
        xhr.responseType = resType; // Default to text when responseType is not set
    //send(data) sends the request to the server. Data for post only

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {

            var res = xhr.response;
            if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) {
                success && success(res);
            } else {
                error && error(res);

Requested json file content

    "name": "yhtx1997",
    "text": "Congratulations on the test!!!"

Call renderings

Posted by lettie_dude on Mon, 02 Dec 2019 20:00:24 -0800