Ajax基础
Ajax基础
1.创建XMLHttpRequest对象现代浏览器中创建一个XMLHttpRequest对象 var xhr = new XMLHttpRequest(); 2.准备请求初始化上一步创建好的对象,这里可以接受三个参数,如下 xhr.open(method,url,async); 第一个参数表示请求类型,GET或者POST。 //GET请求 xhr.open("GET",demo.php?name=tsrot&age=24,true); //POST请求 xhr.open("POST",demo.php,true); 3.发送请求
GET请求 xhr.open("GET",true); xhr.send(null); POST请求 xhr.open("POST",true); xhr.setRequestHeder("Content-Type","application/x-www-form-urlencoded;charset=UTF-8"); xhr.send() 4.处理请求xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(xhr.responseText); } }
5.样例var xhr = false; if( XMLHttpRequest){ xhr = new XMLHttpRequest(); } else{ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(xhr) { //如果xhr创建失败,还是原来的false xhr.open("GET","./data.json",true); xhr.send(); xhr.onreadystatechange = function(){ if(xhr.readyState == 4 && xhr.status == 200){ console.log(JSON.parse(xhr.responseText).name); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |