简体   繁体   中英

passing variable from jQuery ajax to nodejs

i am trying to pass a variable from jQuery to nodejs, but i am not getting the right results, nodejs returns [object Object]. how can it return a string variable on nodejs side.

  $('.test').click(function(){
      var tsId = "Hello World";
      alert(tsId);
      console.log(tsId);
      $.ajax({
        'type': 'post',
        'data':tsId,
        'url': '/test/testing',
        'success': function (data) {
            alert(data);
        }
      })
    });


 router.post('/testing', function(req, res) {

   var tsID = req.body;
   console.log("stsID "+tsID );\\ outputs [object Object]

 });

I recommend you to use this way:

You should pass an object in ajax data , which contains your Hello World string.

$.ajax({
    type: 'post',
    data:{str:tsId},
    url: '/test/testing',
    success: function (data) {
        alert(data);
    }
 });

In node.js file use this:

 router.post('/testing', function(req, res) {
    var tsID = req.body;
    console.log("stsID "+tsID.str );
 });

Try console logging tsID.data or tsID.tsId. What do you get? What do you get if you throw a debugger before your console log and write "tsID" in the console?

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