js-Ajax-get和post請求

1:get請求方式:瀏覽器

// 1:建立XMLHttpRequest對象
var xhr;
if (window.XMLHttpRequest) { // 其餘類型的瀏覽器
    xhr = new XMLHttpRequest();
} else { // ie瀏覽器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2:配置請求信息
xhr.open('get', 'ProcessShow.ashx', true);
// 3:發送請求
xhr.send();
// 4:監聽狀態 註冊onreadystatechange事件
xhr.onreadystatechange = function() {
    // 5:判斷請求和相應是否成功
    if (xhr.readyState == 4 && xhr.status == 200) {
        // 6:獲取數據 並作相應的處理
        var data = xhr.responseText; 
    }
}

Ajax-get.jpg

這是一個完整的Ajax的get請求步驟。ide

若是get請求須要傳遞數據,就這樣寫:post

xhr.open('get', 'ProcessShow.ashx?id=1&name=rose', true);

2:post請求方式:對象

// 1:建立XMLHttpRequest對象
var xhr;
if (window.XMLHttpRequest) { // 其餘類型的瀏覽器
    xhr = new XMLHttpRequest();
} else { // ie瀏覽器
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
// 2:配置請求信息
xhr.open('post', 'ProcessShow.ashx', true);
// 3:發送請求
xhr.send();  // 爲空表示沒有任何的參數
// 4:監聽狀態 註冊onreadystatechange事件
xhr.onreadystatechange = function() {
    // 5:判斷請求和相應是否成功
    if (xhr.readyState == 4 && xhr.status == 200) {
        // 6:獲取數據 並作相應的處理
        var data = xhr.responseText; 
    }
}

Ajax-post.jpg

相關文章
相關標籤/搜索