【问题标题】:Express - How to get serialize formExpress - 如何获取序列化表单
【发布时间】:2017-11-18 16:15:12
【问题描述】:

我正在尝试使用serialize 提交表单,但我无法快速获取数据。

jquery:

    function submitSettingsCustom()
   {
     $('#reception-source-custom-form, expedition-source-custom-form').on("submit", function(event)
     {
       alert("works");
       event.preventDefault();
       var form = $(this).serialize();
       $.post("/add-reception-source-customField/"+ JSON.stringify(form), function(data){

       });
     });
   }

路线:

routes.post('/add-reception-source-customField/:form', settings.storeCustomField);

我正在尝试console.log数组:

console.log(req.params.form);

返回这个:

"name=Emp1&type=submitReceptionSourceCustomFields"

但是如何访问每个值呢?

谢谢

【问题讨论】:

    标签: javascript jquery node.js express


    【解决方案1】:

    您应该将表单数据作为正文添加到 post 请求中,而不是在 url 中

    同样serialize 将产生 urlEncoded 数据,而serializeArray 将产生对象数组。

       function submitSettingsCustom()
       {
         $('#reception-source-custom-form, expedition-source-custom-form').on("submit", function(event)
         {
           alert("works");
           event.preventDefault();
           var form = $(this).serializeArray();
           $.post("/add-reception-source-customField/" , { formData : JSON.stringify(form)}, function(data){
    
           });
         });
       }
    

    然后在 express 中使用 req.body.formData 访问数据

    routes.post('/add-reception-source-customField/', function(req , res){
       console.log(req.body.formData);
    });
    

    【讨论】:

    • 好的 @AmrLabib 但它返回给我这个 "name=Emp1&type=submitReceptionSourceCustomFields" ..
    • 如果您使用我在答案中添加的路线会打印什么?
    • "name=Emp1&type=submitReceptionSourceCustomFields"
    • 现在如果我使用 serializeArray() 会返回:[{"name":"name","value":"Emp1"},{"name":"type","value" :"submitReceptionSourceCustomFields"}] 。有了这个,我现在可以工作了!谢谢
    【解决方案2】:

    对于 HTTP POST 请求,表单数据应在请求正文中而不是 URL 中提交。

    使用 jQuery,这将通过将序列化的表单数据作为第二个参数传递给 $.post() 来完成。

    $.post('/reception-source', $(this).serialize(), function (data) {
      /* lines of code */
    })
    

    在 express 中,您将需要由 Expressjs 团队维护的 body-parser middleware。这个中间件将使表单数据在req.body...

    上可用
    const express = require('express')
    const bodyParser = require('body-parser')
    
    const app = express()
    app.use(bodyParser.urlencoded({ extended: true })
    
    app.post('/reception-source', function (req, res) {
        console.log(req.body)
        /* lines of code */
    })
    

    【讨论】:

    • 它在服务器上给出了 urlencoded 字符串。我怎样才能访问它们。
    猜你喜欢
    • 1970-01-01
    • 2011-05-24
    • 2011-03-26
    • 1970-01-01
    • 2018-06-08
    • 2019-05-20
    • 1970-01-01
    • 2013-12-06
    • 2010-12-20
    相关资源
    最近更新 更多