如何用ajax从前端传一个数组到后端处理,前端使用js,后端为nodejs源码
目录
如何用ajax从前端传一个数组到后端处理,前端使用js,后端为nodejs(源码)
在给后端传输数据时,经常使用的是对象,但是如果需要传一个数组时就需要无法采用常规方法
1、想传一个数组到后端时,无法使用URL路径传参,所以本方法采取正文传参:
//前端js
let arr=[0,1,2,3,4,8,'机会','gggg'];
$.ajax({
url:'/deal',
type:'post',
data:arr,
success:function(data){
console.log(data.message);
}
})
//后端npm
router.post('/',function(request,response){
console.log(request.body);
response.send({
message:'调用成功!'
})
});
结果传到后端的参数打印出来undefined:
2、这样才知道数组不可以直接传,需要转为JSON格式传参
//前端
let arr=[0,1,2,3,4,8,'机会','gggg'];
let arrJSON=JSON.stringify(arr);
$.ajax({
url:'/deal',
type:'post',
data:{
aaa:arrJSON
},
success:function(data){
onsole.log(data.message);
}
});
后端终端输出结果:
3、此时后端终端有返回的数据了,但是我们还需要把数据转化成我们可以用的数据,所以要再把传过来的JSON数据转成js数据
router.post('/',function(request,response){
console.log(request.body);
console.log(JSON.parse(request.body.aaa));
response.send({
message:'调用成功!'
})
});
两者输出结果比较:
这样就可以了
4、附前后端源码
前端:
<script>
$(function(){
// console.log('hhhh');
let arr=['0','1','2','3','4','8','机会','gggg'];
let arrJSON=JSON.stringify(arr);
$.ajax({
url:'/deal',
type:'post',
data:{
aaa:arrJSON
},
success:function(data){
console.log(data.message);
}
})
});
</script>
后端:
//编写后端代码实现用户模块功能
//引入express模块
let express=require('express');
//获取路由对象
let router=express.Router();
router.post('/',function(request,response){
console.log(request.body);
console.log(JSON.parse(request.body.aaa));
response.send({
message:'调用成功!'
})
});
module.exports=router;