如何实现ajax请求?
1、创建XMLHttpRequest实例;
var xhr;if(window.XMLHttpRequest) { //ie7+,firefox,chrome,safari,opera xhr = new XMLHttpRequest();}else { //ie5,ie6 xhr = new ActiveXObject("Microsoft.XMLHTTP");}
2、监听readystatechange事件,并通过readyState属性来判断请求状态;
xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { console.log(xhr.responseText); }}
3、调用open()方法指定请求类型和地址;
xhr.open("GET", "xhr_info.txt");
4、调用send()方法发送请求即可。
xhr.send(null);
完整代码
var xhr; if(window.XMLHttpRequest) { //ie7+,firefox,chrome,safari,opera xhr = new XMLHttpRequest(); } else { //ie5,ie6 xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.onreadystatechange = function() { if(xhr.readyState==4 && xhr.status==200) { console.log(xhr.responseText); } } xhr.open("GET", "xhr_info.txt", true); xhr.send(null);
推荐教程:《JS教程》
以上就是如何实现AJAX请求?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号