例1.$ .ajax(),用于执行异步HTTP请求。所有的jquery ajax。都是用ajax()方法通常用于其他方法不能完成请求。
阿贾克斯在传输数据的时候基本格式大都是固定的,只需要修改传输类型即可。下面介绍基本的参数提交。
步骤一:建立一个HTML或者JSP页面,引入的jquery-3.2.1.min.js(其他版本亦可)。
步骤二:在页面中添加输入框和提交按钮,给予ID值。
步骤三:编写的jquery,AJAX提交数据到指定的控制器。
<!DOCTYPE html>
<html lang="en">
<head>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(function () {
$("#submit").click(function () {
$.ajax({
url: "http://localhost:8080/XXXXXXXX/XXXX/xxxx.do",
type: "POST",
datatype:"JSON",
data: {parameter_A:$("#parameter_A").val(),parameter_B:$("#parameter_B").val()},//发送的数据
success: function (data) {//服务器响应的回来的数据
console.log("");
},
error: function () {
alert("提交失败!");
}
});
});
});
</script>
</head>
<body>
<body>
A:<input type="text" id="parameter_A" value="" /><br /><br />
B:<input type="text" id="parameter_B" value="" />
<input type="button" value="submit" id="submitAB">
</body>
</body>
</html>
2.express响应前端ajax请求
后端其实并不需要知道前端发起的请求是不是ajax,后端只需要响应请求即可.
例子:
前端这样写:
$('button').on('click', function(event) {
event.preventDefault();
/* Act on the event */
$.ajax({
url: '/ajax/test',
type: 'get',
dataType: 'json',
success:function(data){
$('div').html(data.tips);
},
error:function(data){
alert('error');
}
});
});
后端就这么写:
app.get('/ajax/test',function(req,res){
var ajaxTest={
tips:"you are not alone"
};
res.send(ajaxTest);
});
3.
api/user
$.ajax({
请求地址
url:'www.zhouxiaohouer.com/api/user',
请求方式
type:'get',
发送给后端的数据对象
data:{
name:'zhouxiaohouer',
sex:'male'
}
预期服务器返回的数据类型,如果不指定,jQuery会根据响应包自动判断,一般我们直接设定为json
dataType:'json',
成功时候的回调,参数是返回的数据
success:function(res) {
console.log(res.data)
},
失败时回调,参数是一个xhr对象
error:function(err) {
console.log(err.status)
}
})
后端代码
// /api/getsth
// 这里以express某个路由文件说明问题,一级路由是/api
var express = require('express');
var router = express.Router();
router.get('/getsth', function(req, res, next) {
// 是否需要跨域
// res.header('Access-Control-Allow-Origin', '*')
var name = req.query.name
var price = req.query.price
res.json({
status:0,
msg:'success',
data:{
name : name,
price:price
}
})
// req对请求做一些事儿
// res对响应做一些事儿
// next,下一步回调事件
});
router.post('/poststh', function(req, res, next) {
// 是否需要跨域
// res.header('Access-Control-Allow-Origin', '*')
// post请求的参数封装在body中,这里在express中需要使用body-parser在路由前提前进行封装。
var name = req.body.name
var price = req.body.price
res.json({
status:0,
msg:'success',
data:{
name : name,
price:price
}
})
// req对请求做一些事儿
// res对响应做一些事儿
// next,下一步回调事件
});
module.exports = router;
前端代码
$.ajax({
url:'www.zhouxiaohouer.com/api/getsth',
type:'GET',
data:{
name:'番茄炒鸡蛋',
price:45
},
dataType:'json',
success:function(res) {
console.log(res.msg)
console.log(res.data)
},
error:function(err) {
console.log(err.status)
}
})
$.ajax({
url:'www.zhouxiaohouer.com/api/poststh',
type:'POST',
data:{
name:'农家小炒肉',
price:34
},
dataType:'json',
success:function(res) {
console.log(res.msg)
console.log(res.data)
},
error:function(err) {
console.log(err.status)
}
})