我正在使用 Ajax 从客户端成功调用服务器端函数,但我不知道如何通过函数调用传递数组。如您所见,我正在尝试从服务器端的数据标记中获取数据,但没有获取我传递的值。
如何将“hi”、“hello”文本传递给服务器函数?
客户端 Ajax 调用函数:
function ClientSide()
{
var info = [];
info[0] = 'hi';
info[1] = 'hello';
var json = JSON.stringify(info); //pass this
$.ajax({
type: 'post',
url: '/save',
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (html) {
// use data
}
})
}
服务器端功能:
app.post('/save', function(req,res,data)
{
var Passed_value = data;
console.log(Passed_value);
});
首先...您的数据存储在 req.body 中,而不是您添加的第三个参数中。
其次......如果你在字符串中获取JSON,你必须在将其用作对象之前对其进行解析......
代码:
app.post('/save', function(req,res)
{
var Passed_value = JSON.parse(req.body);
console.log(Passed_value);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句