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请求?的详细内容。