1.http请求
<br /><br /><br /><br />
2.get请求
<p id="name"></p>
<p id="age"></p>
<script>
/* JSON.parse() json格式的字符串转换为json对象 */
var url="https://www.easy-mock.com/mock/5d67436224fd60626abfe906/ajax/base";
var xhr=new XMLHttpRequest();
xhr.open('get',url,true) //true 异步
xhr.send()
xhr.onreadystatechange=function(){
/* console.log(xhr.readyState)
console.log(xhr.status) */
if(xhr.readyState==4 && xhr.status==200){ //请求已完成 200:请求成功
var res=JSON.parse(xhr.responseText);
console.log(res.data.name)
var name=document.getElementById("name")
name.innerHTML=res.data.name;
}
}
</script>
JSON.parse()方法将json对象解析为JavaScript对象。
JSON.stringify()将javascript的值,转换为JSON字符串。
2.1responseText:获取字符串形式的响应数据
2.2status:以数字形式返回http的状态码
2.3readystate值代表服务器响应的变化
3.post请求
post方式要设置一个请求头
<div id="test"></div>
<script>
var test = document.getElementById("test");
var xhr = new XMLHttpRequest();
xhr.open("post","https://www.easy-mock.com/mock/5b230e1e6bed703a9b488c69/www.getTest.com/push",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xhr.send(null);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var data = JSON.parse(xhr.responseText);
test.innerHTML = data.data.content
}
}
</script>
4.get和post的区别
1.可见性 get方式传递的参数是跟着url地址后面的;post传递的参数是不可见的<br /> 2.安全性 post更安全<br /> 3.传递数据量大小 get有限制,一般在2000字符左右;post无限制