Ajax请求–get
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><input type="text"></p>
<button>get请求</button>
<div class="box"></div>
</body>
<script type="text/javascript">
var btn=document.querySelector('button');
var box=document.querySelector('.box');
btn.addEventListener('click',function () {
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function () {
console.log(xhr.readyState,xhr.status);
if(xhr.readyState==4 && xhr.status==200){
box.innerText=xhr.responseText;
console.log(xhr.responseText);
console.log(JSON.parse(xhr.responseText));
}
}
xhr.open("GET","http://localhost:3008/api/student/getStudent ");
xhr.send();
})
</script>
</html>
Ajax请求–post
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<p><input type="text"></p>
<button>get请求</button>
<div class="box"></div>
</body>
<script type="text/javascript">
var btn=document.querySelector('button');
var box=document.querySelector('.box');
btn.addEventListener('click',function () {
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function () {
if(xhr.readyState==4 && xhr.status==200){
console.log(xhr.responseText);
box.innerText=xhr.responseText;
}
}
xhr.open("POST","http://localhost:3008/api/student/addStudent ");
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("clazz=虎墩墩&name=小谷&gender=男&age=10&tel=1001&hobby=LOL&address=郑州&remark=其他 ");
})
</script>
</html>