原生Ajax請求

    var Ajax={
        get: function(url, fn) {
            // XMLHttpRequest對象用於在後臺與服務器交換數據
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.onreadystatechange = function() {
                // readyState == 4說明請求已完成
                if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
                    // 從服務器得到數據
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send();
        },
        // datat應爲'a=a1&b=b1'這種字符串格式,在jq裏若是data爲對象會自動將對象轉成這種字符串格式
        post: function (url, data, fn) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", url, true);
            // 添加http頭,發送信息至服務器時內容編碼類型
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
                    fn.call(this, xhr.responseText);
                }
            };
            xhr.send(data);
        }
    }
    Ajax.post('http://127.0.0.1:10001/getTestInfo',{age:12},function (data) {
        data=JSON.parse(data)
        console.log(data);
    })
相關文章
相關標籤/搜索