What is the vanilla JS version of Jquery's $.getJSON

前端 未结 4 1860
礼貌的吻别
礼貌的吻别 2021-02-05 13:07

I need to build a project to get into a JS bootcamp I am applying for. They tell me I may only use vanilla JS, specifically that frameworks and Jquery are not permitted. Up to

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 13:55

    Here is a vanilla JS version of Ajax

    var $ajax = (function(){
        var that = {};
        that.send = function(url, options) {
            var on_success = options.onSuccess || function(){},
                on_error   = options.onError   || function(){},
                on_timeout = options.onTimeout || function(){},
                timeout    = options.timeout   || 10000; // ms
    
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function() {
                if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                    //console.log('responseText:' + xmlhttp.responseText);
                    try {
                        var data = JSON.parse(xmlhttp.responseText);
                    } catch(err) {
                        console.log(err.message + " in " + xmlhttp.responseText);
                        return;
                    }
                    on_success(data);
                }else{
                    if(xmlhttp.readyState == 4){
                        on_error();
                    }
                }
            };
            xmlhttp.timeout = timeout;
            xmlhttp.ontimeout = function () { 
                on_timeout();
            }
            xmlhttp.open("GET", url, true);
            xmlhttp.send();
        }
        return that;
    })();
    

    Example:

    $ajax.send("someUrl.com", {
        onSuccess: function(data){
            console.log("success",data);
        },
        onError: function(){
            console.log("Error");
        },
        onTimeout: function(){
            console.log("Timeout");
        },
        timeout: 10000
    });
    

提交回复
热议问题