js原生ajax请求:get和post
‘get’请求
<script>
window.onload=funciton(){
// 创建ajax对象
var xhr=new XMLHttpRequest();
//配置参数 需要两个1:get;2:url 请求地址
xhr.open('get','url');
//发送请求
xhr.send();
//接收数据
xhr.onload=function(){
//接收到的数据
console.log(xhr.responseText);
}
}
</script>
‘post’请求
需要设置请求头:
xhr.setRequestHeader(‘Content-Type’,‘application/json’)
<script>
window.onload=funciton(){
// 创建ajax对象
var xhr=new XMLHttpRequest();
//配置参数 需要两个1:get;2:url 请求地址
xhr.open('get','url');
//设置请求头 post请求必须要设置的
xhr.setRequestHeader('Content-Type','application/json');
//发送请求
xhr.send();
//接收数据
xhr.onload=function(){
//接收到的数据
console.log(xhr.responseText);
}
}
</script>
‘post’请求示例
工作中post请求用的多,所以演示一个post示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
window.onload = function () {
var btn = document.getElementById("btn");
var username=document.getElementById("username");
var pssword=document.getElementById("password");
var show=document.getElementById("show");
btn.onclick = function(){
var usernameValue=username.value;
var passwordValue=password.value;
//需要传的数据
var obj={ "username":usernameValue,"password":passwordValue};
// 创建ajax post请求的五个步骤
//1:创建Ajax异步对象
var xhr = new XMLHttpRequest();
//2:配置请求方式 请求地址
xhr.open('post', 'http://192.168.1.3:8081/user/login');
// 3:设置请求头
xhr.setRequestHeader('content-type', 'application/json');
//4:转换为JSON数据对象 JSON.parse() 传数据之前要干嘛呢 转换为json数据格式
xhr.send(JSON.stringify(obj));
// 5:接收数据
xhr.onload = function () {
//6:判断是否接收成功
if(xhr.status==200 && xhr.readyState==4){
// 拿到数据并转换为js对象
var info=JSON.parse(xhr.responseText);
console.log(info)
show.innerHTML+="姓名:"+info.data.username+"<br>";
show.innerHTML+="年龄:"+info.data.age+"<br>";
show.innerHTML+="密码:"+info.data.password+"<br>";
show.innerHTML+="性别:";
show.innerHTML+=(info.data.gender==1)?'男':'女';
}else{
alert("数据请求出错!")
}
}
}
}
</script>
</head>
<body>
用户名:<input id="username" type="text" autocomplete="off"><br>
密码:<input id="password" type="text"><br>
<button id="btn">数据请求</button><br>
用户信息:<br>
<h1 id="show"></h1>
</body>
</html>
示例图片
显示的数据就是请求过来的数据
还没有评论,来说两句吧...