passing variable from jQuery ajax to nodejs

狂风中的少年 提交于 2021-02-19 05:24:29

问题


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]

 });

回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/41665948/passing-variable-from-jquery-ajax-to-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!