使用 $.ajax post 将数据发送到 node.js 服务器不工作
Using $.ajax post to send data to node.js server not working
我的目标是将 table 日期转换为数组并使用 Ajax post 将数组发送到服务器端。这是我第一次使用 Ajax post 并且我已经遵循了之前 post 中的所有答案。我仍然不知道缺少什么。我正在使用 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 }));
您的请求正文中没有myTableArray
。
除非您在发送数据时这样做:
$.ajax({
url: "/saler",
type: "POST",
data: {myTableArray},
});
});
然后你可以req.body.myTableArray
阅读myTableArray
。
首先尝试 console.log(req.body)
检查请求中的数据结构。
我的目标是将 table 日期转换为数组并使用 Ajax post 将数组发送到服务器端。这是我第一次使用 Ajax post 并且我已经遵循了之前 post 中的所有答案。我仍然不知道缺少什么。我正在使用 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 }));
您的请求正文中没有myTableArray
。
除非您在发送数据时这样做:
$.ajax({
url: "/saler",
type: "POST",
data: {myTableArray},
});
});
然后你可以req.body.myTableArray
阅读myTableArray
。
首先尝试 console.log(req.body)
检查请求中的数据结构。