如何用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;

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值