【问题标题】:How to send data using ajax to a node server without jquery?如何使用 ajax 将数据发送到没有 jquery 的节点服务器?
【发布时间】:2019-07-09 06:51:23
【问题描述】:

我正在尝试学习如何使用 ajax 发送数据。单击提交按钮时,我希望 Ajax 将数据发送到与数据无关的特定路由以及与表单关联的路由。然而,Ajax 似乎没有发送任何东西。我在脚本中添加了三个 console.log() 语句,但没有一个被显示。

HTML 和 AJAX 代码

<head>
  <meta charset="utf-8">
  <title></title>
</head>

<body>

  <form class="" action="/submitData" method="post">
    <input type="text" name="name">
    <button id="submitForm" type="submit">Submit</button>

    <script>
      const el = document.getElementById(submitForm);
      if (el) {
        el.addEventListener('submit', addRecipe);
        console.log('Step 1');
      }


      function addRecipe() {

        var recipe = {
          param1: 'value1',
          param2: 'value2'
        };

        console.log('step 2')

        let xml = new XMLHttpRequest();
        xml.open("POST", "/add-recipe", true);
        //Specify the type of data to be sent
        xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xml.send(JSON.stringify(recipe));
        console.log('step 3');
        }
    </script>
</body>

</html>

server.js 文件

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
let urlencodedParser = bodyParser.urlencoded({extended: false});

app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

app.listen(7000);

app.post('/add-recipe', function(req, res) {
  var recipe = req.body.recipe;
  console.log(recipe);
});

app.post('/submitData',urlencodedParser,function(req, res){

});

【问题讨论】:

    标签: javascript html node.js ajax


    【解决方案1】:

    您需要将type="button" 添加到您的提交按钮并使用preventDefault 发出xmlhttp 请求...

    const el = document.getElementById("submitForm");
          if (el) {
            el.addEventListener('click', addRecipe);
            console.log('Step 1');
          }
    
    
          function addRecipe(e) {
            e.preventDefault();
            var recipe = {
              param1: 'value1',
              param2: 'value2'
            };
    
            console.log('step 2')
    
            let xml = new XMLHttpRequest();
            xml.open("POST", "/add-recipe", true);
            //Specify the type of data to be sent
            xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
            xml.send(JSON.stringify(recipe));
            console.log('step 3');
            }
    <head>
      <meta charset="utf-8">
      <title></title>
    </head>
    
    <body>
    
      <form class="" action="/submitData" method="post">
        <input type="text" name="name">
        <button id="submitForm" type="submit" type="button">Submit</button>
    
      </form>
    </body>

    【讨论】:

    • 我从来不知道你可以将不止一种类型附加到一个元素上。谢谢你。但是,能否更新您的答案并解释为什么将 type ="submit 附加到表单和监听器都不起作用?另外,您能否解释一下 e.preventDefault(); 的作用以及为什么需要它?
    【解决方案2】:

    其实当点击submit按钮时,会提交form,所以页面/数据会直接重定向到action页面。

    这就是为什么您的addRecipe() 函数没有执行的原因,因为页面在执行之前被重定向。

    所以如果你想在提交表单之前执行addRecipe()函数并通过Ajax发送data,你需要阻止默认的表单提交,执行你的代码然后提交form

    function addRecipe(e) {
    
        e.preventDefault();
    
        var recipe = {
          param1: 'value1',
          param2: 'value2'
        };
    
        console.log('step 2')
    
        let xml = new XMLHttpRequest();
        xml.open("POST", "/add-recipe", true);
        //Specify the type of data to be sent
        xml.setRequestHeader("Content-type", "application/json; charset=utf-8");
        xml.send(JSON.stringify(recipe));
        console.log('step 3');
    
        //Get the form and submit it
        form.submit();
    }
    

    【讨论】:

      猜你喜欢
      • 2020-08-31
      • 2013-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-22
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多