发送Ajax请求包含文件为
原声Ajax的get请求
前端HTML
<style>
button{
margin-left: 45%;
margin-top: 100px;
}
#result{
width: 200px;
height: 200px;
margin: 10px auto;
border:2px solid cadetblue;
}
</style>
<button>点击发送请求</button>
<div id="result"></div>
<script>
const btn=document.querySelector('button');
const result=document.getElementById('result');
btn.onclick = function (){
//1.创建对象
const xhr = new XMLHttpRequest();
//2.初始化 如果是post只需要GET改为POST即可
xhr.open('GET','http://127.0.0.1:8000/server');
//3.发送
xhr.send();
//4.进行事件绑定
xhr.onreadystatechange = function (){
if (xhr.readyState===4){
if (xhr.status>=200 &&xhr.status<=300){
console.log(xhr.response)
result.innerHTML=xhr.response;
}
}
}
}
</script>
jquery和aixos发送ajax请求方式
前端HTML
<button id="btn">点击发送请求</button>
<div id="result"></div>
<script>
const btn=document.querySelector('button');
const result=document.getElementById('result');
//使用jquery发送
$('#btn').onclick(function (){
alert("到外层了");
$.get('http://127.0.0.1:8000/json',function (){
alert('json传值')
})
})
//使用axios发送请求
axios.defaults.baseUrl = 'http://127.0.0.1:8000';
btn[0].onclick = function (){
//get请求
axios.get('/axios-server',{
//url参数
param:{
id:100,
vip:7
},
//请求头
headers:{
name:'atguigu',
age:20
},
//请求体
data:{
}
}).then(value => {
console.log(value);
});
}
// btn.onclick = function (){
// //1.创建对象
// const xhr = new XMLHttpRequest();
// //2.初始化
// xhr.open('POST','http://127.0.0.1:8000/json');
// //3.发送
// xhr.send();
// //4.进行事件绑定
// xhr.onreadystatechange = function (){
// if (xhr.readyState===4){
// if (xhr.status>=200 &&xhr.status<=300){
// console.log(xhr.response)
// result.innerHTML=xhr.response;
// }
// }
// }
// //
// }
</script>
server.js内容
//1.引入express
const express=require('express');
//创建app应用
const app=express();
//设置请求参数
//app.all可以接收任意的请求
app.post('/server',(request,response)=>{
//设置响应头
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
response.send('HELLO AJAX')
})
app.all('/json',(request,response)=>{
//设置响应头 此处也使用了cros解决跨域问题
response.setHeader('Access-Control-Allow-Origin','*');
//设置响应体
const data ={
name:'atguigu'
}
let str=JSON.stringify(data);
response.send(str)
})
//设置监听端口
app.listen(8000,()=>{
console.log("服务已经启动")
})