简体   繁体   English

使用Ajax,jquery,Node.js和Express发布POST数据

[英]POST data using Ajax, jquery, Node.js and Express

I need some help. 我需要协助。 I'm trying to get this done following different things I've found over the internet but I can't understand the process. 我试图通过互联网上发现的不同事情完成这项工作,但我无法理解这个过程。 I have a carousel where my users is redirect to right after the signup. 我有一个旋转木马,我的用户在注册后重定向到了。 I'm tying to get informations about their profile by asking simple questions as inputs. 我想通过简单的问题作为输入来获取关于他们的个人资料的信息。 This is the Pug code 这是帕格代码

body
div(class='container fill')
  div(id='myCarousel', class='carousel slide', data-ride='carousel', data-interval="false", data-wrap="false")
    div(class='carousel-inner')
      div(class='item active')
        div(class='carousel-caption')
          div(class='form-group', method='post')
            h1(id='welcome') WELCOME 
            h1
            | Tell us more about yourself
          h2
            | Pick any interest you like
          label(for='shopping', class="radio-inline")
            | Shopping
          input(type='checkbox', id='round', name='interest_filter', value='2', checked=interest=='shopping')

          div
          label(for='travelling', class="radio-inline")
            | Travelling
          input(type='checkbox', id='round', name='interest_filter', value='3', checked=interest=='travelling')

          div
          label(for='musique', class="radio-inline")
            | Musique
          input(type='checkbox', id='round', name='interest_filter', value='4', checked=interest=='musique')

          div
          label(for='cooking', class="radio-inline")
            | Cooking
          input(type='checkbox', id='round', name='interest_filter', value='5', checked=interest=='cooking')

          div
          label(for='nature', class="radio-inline")
            | Nature
          input(type='checkbox', id='round', name='interest_filter', value='6', checked=interest=='nature')

          div
          label(for='arts', class="radio-inline")
            | Arts
          input(type='checkbox', id='round', name='interest_filter', value='7', checked=interest=='arts')

And this is where I have no idea how to give the data 这是我不知道如何提供数据的地方

$('#matchme').click(function(){
var data = {};

$.ajax({
       url: '/carousel',
       type: 'POST',
       cache: false,
       data: JSON.stringify(data),
       success: function(data){
          alert('post success')
          console.log(JSON.stringify(data));
        }
      });
 });

This is in my app.js (I will use a waterfall to get thought the data and store it in my db) 这是在我的app.js(我将使用瀑布来考虑数据并将其存储在我的数据库中)

app.post('/carousel', function (req, res) {
var data = {
interests: req.body.interest_filter,
orientation: req.body.orientation_filter,
age: req.body.age
 },
});

I'm using inputs because you can't put a form in a carousel. 我正在使用输入,因为你不能把表格放在旋转木马上。 So far I understand the concept, but I've been using Javascript for a month now and I'm stuck, any help please ? 到目前为止,我理解这个概念,但我现在已经使用Javascript一个月而且我被卡住了,请帮忙吗? Thanks in advance ! 提前致谢 !

First you have to collect all the informations from user and pass that object in Ajax call. 首先,您必须从用户收集所有信息并在Ajax调用中传递该对象。 And I don't see any data you are passing during request except blank object. 除了空白对象之外,我没有看到您在请求期间传递的任何数据。 After that on server side you can get all the informations in req.body as you have already written.. 在服务器端之后,您可以获得req.body所有信息,就像您已经编写过的那样。

     $('#matchme').click(function(){
         var data = {name:'hola', info: 'info'};

      $.ajax({
        url: '/carousel',
        type: 'POST',
        cache: false,
       data: JSON.stringify(data),
        success: function(data){
           alert('post success')
           console.log(JSON.stringify(data));
        }
       });
   });

First of all, I would recommend using the class attribute instead of id to apply the style of "round" to each of the elements, if im understanding the question correctly. 首先,如果我正确理解问题,我建议使用class属性而不是id将“round”样式应用于每个元素。

If you change that, you are able to use the vanilla JavaScript: document.getElementById('someId').value syntax to extract the different values? 如果你改变了,你可以使用vanilla JavaScript: document.getElementById('someId').value语法来提取不同的值?

If you are using JQuery library, it is even easier: $( "#someId" ).val(); 如果您使用的是JQuery库, $( "#someId" ).val();容易: $( "#someId" ).val(); http://api.jquery.com/val/ http://api.jquery.com/val/

Thanks you for your help I get the concept now. 谢谢你的帮助我现在得到了这个概念。 It as been working so far with this : 它到目前为止一直在用这个:

$(document).ready(function() {
console.log("document is ready");
$("#matchme").click(function(){
event.preventDefault();
var data = {};
data.sex = $('[name=sex]:checked').val();
data.orientation_filter = $('[name=orientation_filter]:checked').val();
data.age = $('[name=age]:checked').val();

console.log(data.sex);
console.log(data.orientation);
console.log(data.age);
$.ajax({
         url: '/carousel',
         type: 'POST',
         cache: false,
         data: JSON.stringify(data),
         success: function(data){
            alert("post success")
            console.log(JSON.stringify(data));
          }
        });
   });

});

So I can get the value of data.sex when I log it but the two others data.orientation and data.age are still undefined. 因此,当我记录它时,我可以获得data.sex的值,但另外两个data.orientation和data.age仍未定义。

Here is my app.js file for this post : 这是我的app.js文件:

app.post('/carousel', function (req, res) {
username = session.uniqueID;
var data = {
sex: req.body.sex,
orientation: req.body.orientation_filter,
age: req.body.age
};
console.log(data.sex);
console.log(data.age);
function UserStart(data, callback) {
async.waterfall([
  function(cb) {
    pool.getConnection(function (err, connection) {
      if (err) {
        console.log(err);
      }
      connection.query('INSERT INTO usersinfo SET ?', data , function (err, rows, fields) {
        if (err) {
          console.log(err, "error")
        } else {
          callback(null, "all good")
        }
      });
    });
  }
],
function (err, data) {
  if (err) {
    callback(err);
  } else {
    callback(null, data);
  }
})
}
UserStart(data, function (err, callback) {
 if (err) {
   res.redirect('/login');
   console.log("login again");
 } else {
   res.redirect('/home');
   console.log("user is now activated, ready !");
 }
})
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM