将变量从jQuery ajax传递到nodejs

问题描述:

我正在尝试将jQuery中的变量传递给nodejs,但是我没有得到正确的结果,nodejs返回[object Object].如何在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:

您应该在ajax data 中传递一个对象,该对象包含您的 Hello World 字符串.

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);
    }
 });

在node.js文件中使用以下命令:

In node.js file use this:

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