原生post請求


ajax: function(opt) {
        opt = opt || {};
        opt.method = opt.method.toUpperCase() || 'POST';
        opt.url = opt.url || ''; //請求地址
        opt.async = opt.async || true; //是否異步請求
        opt.data = opt.data || null; //傳輸數據
        opt.success = opt.success || function() {}; //服務器響應成功進行相應的處理
        var xmlHttp = null;
        if (XMLHttpRequest) {
            xmlHttp = new XMLHttpRequest(); //服務器請求對象
        } else {
            xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); //兼容微軟請求對象
        }
        var params = [];
        for (var key in opt.data) {
            // params.push(key + '=' + opt.data[key]);
            params.push(encodeURIComponent(key) + '=' + encodeURIComponent(opt.data[key]));
        }
        var postData = params.join('&');
        if (opt.method.toUpperCase() === 'POST') {
            //請求方法為POST,則執行如下操作
            xmlHttp.open(opt.method, opt.url, opt.async);
            xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
            xmlHttp.send(postData);
        } else if (opt.method.toUpperCase() === 'GET') {
            //請求方法為GET,則執行如下操作
            xmlHttp.open(opt.method, opt.url + '?' + postData, opt.async);
            xmlHttp.send(null);
        }
        xmlHttp.onreadystatechange = function() {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                //響應是否成功
                var data = JSON.parse(xmlHttp.responseText);
                opt.success(data);
            }
        };
    },

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM