第1讲:XMLHttpRequest详解(ajax基础)
    		       		warning:
    		            这篇文章距离上次修改已过434天,其中的内容可能已经有所变动。
    		        
        		                
                XMLHttpRequest对象是Ajax技术的核心,它能够使页面的某部分更新,而不需要重新加载整个页面。
以下是创建XMLHttpRequest对象的方法:
var xhr;
if (window.XMLHttpRequest) { // 现代浏览器
    xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // 旧版IE
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}以下是使用XMLHttpRequest对象发送GET请求的方法:
xhr.open('GET', 'your-url', true); // 打开连接
xhr.send(); // 发送请求
xhr.onreadystatechange = function () { // 监听状态变化
    if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功完成
        var response = xhr.responseText; // 获取响应文本
        console.log(response);
    }
};以下是使用XMLHttpRequest对象发送POST请求的方法:
xhr.open('POST', 'your-url', true); // 打开连接
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头
xhr.send('param1=value1¶m2=value2'); // 发送请求
xhr.onreadystatechange = function () { // 监听状态变化
    if (xhr.readyState === 4 && xhr.status === 200) { // 请求成功完成
        var response = xhr.responseText; // 获取响应文本
        console.log(response);
    }
};这些是创建XMLHttpRequest对象和使用它发送GET和POST请求的基本方法。在实际应用中,你可能还需要处理更复杂的情况,例如处理响应数据、设置超时、处理错误等。
评论已关闭