原生JavaScript寫AJAX

前端JavaScript:

function ajaxGet(url, obj) {
    var request;
    if(window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    } else {
        request = new ActiveXObject('Microsoft.XMLHTTP'); // 兼容IE
    }

    request.onreadystatechange = function() {
        if(request.readyState === 4) { // 4 請求完成
            if(request.status === 200) { // 200 頁面成功加載
                console.log(request.responseText); // 成功 返回得到的文本
            } else {
                console.log(request.status); // 失敗 返回狀態碼 如 404
            }
        } else {
            console.log('Requesting');
        }
    }
    /* 解析參數 */
    str = '?';
    for(key in obj) {
        str += (key + '=' + obj[key] + '&');
    }
    str = str.substr(0, str.length - 1);
    /* 發送 */
    request.open('GET', url + str);
    request.send();
}

ajaxGet('ajax.php', {
    'type': 'get',
    'data': 'test'
}); //get-test

後端PHP:

<!-- ajax.php -->
<?php
    echo $_GET['type'] . '-' . $_GET['data'];

原生JavaScript寫AJAX

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章