ajax and JSON requests -- encapsulation

Keywords: JSON Firefox Javascript

ajax:

function ajax(opt) {

    //Intercession path
    var url;
    if(opt.url){
        url = opt.url;
    }else{
        console.log('Please enter the request path');
    }
    //Request type
    var type = opt.type || 'GET';
    //Callback function
    var callback = opt.callback || function (msg) {  };
    //Request data
    var data = opt.data || [];
    //Piecing together courtship data
    var str = '';
    for(var k in data){
        str += k + '=' + data[k] + '&';
    }
    str = str.slice(0,str.length-1);
    console.log(str);


    // 1. Create object
    var xmlhttp;
    if (window.XMLHttpRequest)
    {
        //  IE7+, Firefox, Chrome, Opera, Safari browser execution code
        xmlhttp = new XMLHttpRequest();
    } else {
        // IE6, IE5 browser execution code
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }


    // 2. Send request

    // get requests and post requests
    if(type == 'GET'){
        //When there is request data
        if(data.length > 0){
            var nowUrl = url + '?' + str;
            xmlhttp.open(type,url,true);
            xmlhttp.send();
        }else{
            xmlhttp.open(type,url,true);
            xmlhttp.send();
        }
    }else{
        //When there is request data
        if(data.length > 0){
            xmlhttp.open(type,url,true);
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(str);
        }else{
            xmlhttp.open(type,url,true);
            xmlhttp.send();
        }
    }


    // 3. Server response
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            callback(xmlhttp.responseText);
        }
    }
}

usage method:

ajax({
    type:'POST',
    data:{
        name:'zhangsan',
        age:20
    },
    url:'zz.text',
    callback:function(opt){
        console.log(opt)
    }
})

jsonp:

jsonp simple version:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>JSONP Example</title>
    <style>
        .jsonp{
            display: inline-block;
            padding: 5px 10px;
            background-color: aqua;
            border-radius: 6px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<span class="jsonp">jsonp</span>
<div id="divCustomers"></div>
<script type="text/javascript">
    function jsonp1(result) {
        console.log(result);
    }

    function beginJsonp(req) {
        var script = document.createElement('script');
        var url = req.url + '?jsonpCallback=' + req.callback;
        script.src = url;
        document.querySelector('head').appendChild(script);
        document.querySelector('head').removeChild(script);
    }

    document.querySelector('.jsonp').onclick = function () {
        beginJsonp({
            url:'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg',
            callback:'jsonp1'
        });
    };
</script>
</body>
</html>

The essence is to create a script tag. The src address is the request address. (the principle is that script can be used for cross domain access, and people who want to know can baidu)

JSON enhanced version:

(function (globalObj) {

    function jsonp(opt) {
        var head = document.querySelector('head');

        var url = opt.url || '';

        // Splicing data, if any
        var data = opt.data || {};
        //If data has content
        var dataStr = '';
        if(commonFun.isEmptyObj(data)){
            for(var k in data){
                dataStr += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
            }
            //Remove from last&
            dataStr = dataStr.slice(0,str.length - 1);
        }

        //Global temporary jsonpCallback, calling the backfill function
        var callback = opt.callback || function (transaction) {  };
        globalObj.jsonpCallback = function (res) {
            callback(res);
            delete globalObj.jsonpCallback;
        };
        // globalObj.jsonpCallback = callback || function (transaction) {  };

        // Final url splicing
        url += '?' + dataStr + 'jsonpCallback=jsonpCallback';


        //Generate script
        var script = document.createElement('script');
        script.src = url;
        head.appendChild(script);
        head.removeChild(script);
    }

    globalObj.jsonp = jsonp;
})(window)

When using, call the following methods

jsonp({
    url:'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg',
    data:{
        g_tk:5381,
        uin:0,
        format:'json'
    },
    callback:function (res) {
        console.log(res)
    }
});

In jsonp, the last function in script is just a function name. That function must be a global function. There are too many global functions. Therefore, a temporary jsonp callback function is defined here. The callback function is called in the temporary function. After the global temporary function is removed, no pollution will be caused.

jsonp intelligent get requests are generally not needed. They are written directly at the back end, and the front end can be written directly with ajax. cors, you can have a look

Posted by FraXTC on Mon, 30 Dec 2019 08:51:39 -0800