简体   繁体   中英

NodeJS - Pass an array from client to server with ajax

I am successfully calling a server side function from the client side with Ajax, but i cant figure out how to pass an array with the function call. As you can see, i am trying to get data out of the data tag on the server side but i am not getting the values i passed.

How do i get the "hi", "hello" text passed to the server function?

Client Side Ajax Calling Function:

function ClientSide()
{
    var info = [];
    info[0] = 'hi';
    info[1] = 'hello';

    var json = JSON.stringify(info); //pass this

    $.ajax({
        type: 'post',
        url: '/save',
        data: json,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (html) {
            // use data
        }
    })
}

Server Side Function:

app.post('/save', function(req,res,data)
{
    var Passed_value = data;
    console.log(Passed_value);
});

First... your data is stored in req.body, not in third argument that you added.

Second... if you are getting JSON in string, you got to parse it before using it as an object...

Code:

app.post('/save', function(req,res)
{
    var Passed_value = JSON.parse(req.body);
    console.log(Passed_value);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM