How to use ajax to pass an array from the front end to the back end for processing, the front end uses js, and the back end uses nodejs (source code)

When transferring data to the backend, objects are often used, but if an array needs to be passed, conventional methods cannot be used

1. When you want to pass an array to the backend, you cannot use the URL path to pass parameters, so this method uses text to pass parameters:

//前端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:'调用成功!'
    })
});

As a result, the parameters passed to the backend are printed as undefined:

 2. Only in this way can we know that the array cannot be passed directly, and it needs to be converted to JSON format to pass parameters

//前端
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);
    }
});

Backend terminal output result:

3. At this time, the back-end terminal has returned data, but we still need to convert the data into usable data, so we need to convert the passed JSON data into js data

router.post('/',function(request,response){
    console.log(request.body);
    console.log(JSON.parse(request.body.aaa));
    response.send({
        message:'调用成功!'
    })
});

Compare the output of the two:

that's it 

4. Attach the front-end and back-end source code

front end:

<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>

rear end:

//编写后端代码实现用户模块功能
//引入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;

Guess you like

Origin blog.csdn.net/wzy_PROTEIN/article/details/125413613