【问题标题】:Ajax call in node.jsnode.js 中的 Ajax 调用
【发布时间】:2018-09-01 06:53:19
【问题描述】:

大家好,我在使用 ajax 调用方面遇到了问题。

我有两个 ajax 调用,所以第一个 ajax 将数据发送到服务器,服务器检查并返回值,我希望返回值到另一个 ajax 调用,但似乎我在第二个 ajax 调用中没有传递任何内容。

第一次 Ajax 调用

function first(){

  $.ajax({
    url:window.location + '/first',
    type: 'post',
    data : $('form#first_form').serialize() //it will be like "name=Brad",
    success: function(response){   
      consol.log(response.name); // I checked, and it returns "Brad"

      second_ajax(response.name); //pass the returned value "Brad"

    },error: function(){

    }
  });
}

第二次 Ajax 调用

function second(response_name){

  $.ajax({
    url:window.location + '/second',
    type: 'get',
    data : {username:response_name}//I am not sure how to write here, I want to send like 'username=Brad'
    success: function(result){ 
    },error: function(){

    }
  });
}

服务器

 app.get('/second', (req, res) => {
          //get the username from the second ajax call
          var user_name = req.body.username;} //I am getting nothing here...

【问题讨论】:

    标签: javascript jquery node.js ajax


    【解决方案1】:

    req.body.username 仅在您使用 body-parser 中间件并且请求是 POST 时才有效。 req.body 将是 POST 请求的解析正文。

    如果数据在 GET 的查询字符串(例如查询参数)中,看起来像你的,那么你想要:

    req.query.username
    

    你可以这样合并:

    app.get('/second', (req, res) => {
          //get the username from the second ajax call
          var user_name = req.query.username;} //I am getting nothing here..
          console.log(user_name);
          res.send("got it");
    });
    

    这是Express doc for req.query

    而且,您可以在 jQuery doc for $.ajax() 中看到 data 选项将内容放入查询字符串中。

    【讨论】:

    • 是的,我正在等待时间限制,它一直说我可以在某些分钟后选择你的答案哈哈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-19
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多