GET请求
jQuery发送Ajax请求时,函数有三个参数,第一个是请求的URL地址,第二个是请求参数,第三个是一个回调函数,回调函数的参数是服务器端返回的结果。
server.js部分
app.all('/jquery',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*');
const data={
name:'zhangsan'
}
res.send(JSON.stringify(data))
});
$('span').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery',{a:100},function(data){
console.log(data)//{"name":"zhangsan"}
})
})
jQuery对json数据进行处理的操作:
$('span').eq(0).click(function(){
$.get('http://127.0.0.1:8000/jquery',{a:100},function(data){
console.log(data)//{name: "zhangsan"}
},'json')
})
POST请求
$('span').eq(1).click(function(){
$.post('http://127.0.0.1:8000/jquery',{a:100},function(data){
console.log(data)
})
})
通用方法
$('span').eq(2).click(function(){
$.ajax({
url:'http://127.0.0.1:8000/jquery',
data:{a:100},
type:'GET',
// dataType:'json',
success:function(data){
console.log(data)
},
// 失败的回调
error:function(){
console.log('出错啦')
},
// 超时时间
timeout:2000,
// 头信息
headers:{
b:2
}
})
})