【问题标题】:Using $.ajax post to send data to node.js server not working使用 $.ajax post 将数据发送到 node.js 服务器不起作用
【发布时间】:2020-03-16 16:14:07
【问题描述】:

我的目标是将表格日期转换为数组,并使用 Ajax post 将数组发送到服务器端。这是我第一次使用 Ajax 帖子,我已经按照之前帖子中的所有答案进行了操作。我仍然不知道缺少什么。我正在使用 body-parser 来获取服务器端的数据。我将不胜感激任何帮助或如果有另一种更简单的方法将数组发送到服务器端。当我尝试打印输出时,我当前的输出未定义。请参阅下面的代码:

ejs端

<table id="cartGrid">
        <thead>
             <tr>
                <th>Item Description</th>
                <th>Qty</th>
                <th>Unit Price</th>
                <th>Ext Price</th>
             </tr>
        </thead>
        <tbody>
          <tr><td>Old Lamp</td><td>1</td><td>107.00</td><td>107.00</td>
          <tr><td>Blue POst</td><td>2</td><td>7.00</td><td>14.00</td>
   </tbody>
</table>

<script>
// convert table to array

    var myTableArray = [];
    $("table#cartGrid tr").each(function() { 
    var arrayOfThisRow = [];
    var tableData = $(this).find('td');
    if (tableData.length > 0) {
        tableData.each(function() { arrayOfThisRow.push($(this).text()); });
        myTableArray.push(arrayOfThisRow);
    }

// post the data
$.ajax({
        url: "/saler",
        type: "POST",
        data: myTableArray,
    });

});

</script>

服务器端

router.post('/saler', function (req, res, next) {
  var myTableArray = req.body.myTableArray;
  console.log(myTableArray);
});

app.js

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

【问题讨论】:

    标签: javascript node.js ajax body-parser


    【解决方案1】:

    您的请求正文中没有myTableArray

    除非您在发送数据时这样做:

    $.ajax({
            url: "/saler",
            type: "POST",
            data: {myTableArray},
        });
    
    });
    
    

    然后您可以通过req.body.myTableArray 阅读myTableArray

    首先尝试console.log(req.body) 检查您请求中的数据结构。

    【讨论】:

    • 谢谢,它有效。但是当我加载页面时,我有一个帖子立即工作的问题。请问我该如何防止这种情况?我更喜欢它仅在单击按钮时才起作用。谢谢。
    • @NaheemOlaniyan 在您的页面中添加一个按钮。添加点击事件监听器&lt;button onclick=postMethod&gt;Send&lt;/button&gt;postMethod 是你打电话给$.ajax
    • 知道了。非常感谢。
    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2019-03-16
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    相关资源
    最近更新 更多