撒拉嘿哟木头 2018-08-31 22:50 采纳率: 100%
浏览 111

node.js中的Ajax调用

Hi guys I am having a issue in terms of using ajax call.

I have two ajax calls so first ajax sends the data to the server and server checks and return the value and I want the returned values to the another ajax call but it seems like I am passing nothing in second ajax call.

First Ajax Call

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(){

    }
  });
}

Second Ajax call

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(){

    }
  });
}

Server

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

1条回答 默认 最新

  • MAO-EYE 2018-08-31 22:53
    关注

    req.body.username only works if you're using the body-parser middleware and the request was a POST. req.body would be the parsed body of the POST request.

    If the data is in the query string (e.g. a query parameter) of a GET which it looks like yours is, then you want:

    req.query.username
    

    And you could incorporate that like this:

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

    Here's the Express doc for req.query.

    And, you can see in the jQuery doc for $.ajax() that the data option puts things into the query string.

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?