如果要想详细了解ajax,点击菜鸟教程链接 http://www.runoob.com/ajax/ajax-tutorial.html,
在这我不做详细的介绍
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax</title>
</head>
<body>
// 给三个点击事件
<button id="myGet">get-ajax</button>
<button id="myPost">post-ajax</button>
<button id="myAjax">ajax</button>
</body>
//导入jquery
<script src="jquery.js"></script>
<script>
// get
// 给事件一个点击事件
$('#myGet').click(function(){
// alert('点击了')
// 回调函数 里面三个参数 data 是回调的数据, status状态 ,xhr 是ajax的核心 XMLHttpRequest
$.get('/getTest',{name:'小明',age:17},function(data,status,xhr){
console.log(data)
})
})
// post请求
$('#myPost').click(function(){
$.post('/postTest',{name:"小王",age:16},function(data){
console.log(data)
})
})
// ajax
$('#myAjax').click(function(){
$.ajax({
// 请求地址,接口
url:'/ajaxTest',
// 请求的参数,内容
data:{name:'ajax',des:'这是我的第一个ajax请求'},
// 请求的类型 默认是get 可以不写
type:'post',
// 设置超时时间
timeout:1000*30,
// 接收数据成功 data为接收的内容
success:function(data){
console.log('success接收成功')
console.log('接受的内容:'+data)
},
// 接收数据失败
error:function(data){
console.log('error')
console.log(data)
},
// 发送数据之前
beforeSend:function(){
console.log('哈哈哈要发送了')
},
// 发送完成
complete:function(){
console.log('complete'+'发送完成')
}
})
})
</script>
</html>
后端:
//导入需要模块
var express = require('express')
var bodyParser = require('body-parser')
var web = express()
web.use(express.static('public'))
web.use(bodyParser.urlencoded({extended:false}))
// ajax —— get方法
web.get('/getTest',function(req,res){
var name =req.query.name
var age = req.query.age
res.send('发送的数据是:'+name + ',' + age)
})
// ajax —— post方法
web.post('/postTest',function(req,res){
var name = req.body.name
var age = req.body.age
res.send('发送的数据是:'+name + '.' +age)
})
// ajax 方法
web.post('/ajaxTest',function(req,res){
var des = req.body.des
res.send('发送的数据是:'+des)
})
web.listen('8080',function(){
console.log('服务器已经开启...')
})