使用此代码,我创建了一个创建一些JSON数据并将其发送到server.js(我的节点服务器)的函数。
function deleteEmail(i) {
emailObj.splice(i, 1);
var general = {};
var table = []
general.table = table;
for (var i = 0; i < emailObj.length; i++) {
var dataHtml = emailObj[i].html;
var html = {
"html": dataHtml
}
general.table.push(html);
}
console.log(JSON.stringify(general));
$.post("email2", general);
}
server.js中用于捕获JSON数据的代码是:
app.post("/email2", function(req, res){
console.log(req.body);
});
这是函数创建并发送到server.js的JSON数据:
{"table":[{"html":"<b>ID email:</b> #1481145671503<br><b>Form journey:</b> General<br><b>Work Request Title:</b> <br><b>Data Request:</b> <br><b>Request By:</b> <br><b>Department:</b> <i>not specified</i><br><b>Business Owner:</b> <br><b>Contact Details:</b> <br><b>Request Overview:</b> <br><b>Platform Impacted:</b> undefined<br><b>Business Objectives:</b> <br><b>Business Benefits Justifications:</b> <br><b>Project Drive:</b> <br><b>Additional Information:</b> <br>"},{"html":"<b>ID email:</b> #1481214851188<br><b>Date:</b> Thu Dec 08 2016 16:34:11 GMT+0000 (GMT)<br><b>Form journey:</b> General<br><b>Work Request Title:</b> <br><b>Data Request:</b> <br><b>Request By:</b> <br><b>Department:</b> <i>not specified</i><br><b>Business Owner:</b> <br><b>Contact Details:</b> <br><b>Request Overview:</b> <br><b>Platform Impacted:</b> undefined<br><b>Business Objectives:</b> <br><b>Business Benefits Justifications:</b> <br><b>Project Drive:</b> <br><b>Additional Information:</b> <br>"}]}
这是服务器正在接收的JSON数据:
{ 'table[0][html]': '<b>ID email:</b> #1481145671503<br><b>Form journey:</b> General<br><b>Work Request Title:</b> <br><b>Data Request:</b> <br><b>Request By:</b> <br><b>Department:</b> <i>not specified</i><br><b>Business Owner:</b> <br><b>Contact Details:</b> <br><b>Request Overview:</b> <br><b>Platform Impacted:</b> undefined<br><b>Business Objectives:</b> <br><b>Business Benefits Justifications:</b> <br><b>Project Drive:</b> <br><b>Additional Information:</b> <br>',
'table[1][html]': '<b>ID email:</b> #1481214851188<br><b>Date:</b> Thu Dec 08 2016 16:34:11 GMT+0000 (GMT)<br><b>Form journey:</b> General<br><b>Work Request Title:</b> <br><b>Data Request:</b> <br><b>Request By:</b> <br><b>Department:</b> <i>not specified</i><br><b>Business Owner:</b> <br><b>Contact Details:</b> <br><b>Request Overview:</b> <br><b>Platform Impacted:</b> undefined<br><b>Business Objectives:</b> <br><b>Business Benefits Justifications:</b> <br><b>Project Drive:</b> <br><b>Additional Information:</b> <br>' }
为什么要这样做?如何在发送时保留完全相同的格式和数据,并通过server.js对其进行解释。
由于
答案 0 :(得分:0)
您永远不会将JSON数据发送到服务器。
console.log(JSON.stringify(general));
在上面一行中你:
general
,一个JavaScript对象$.post("email2", general);
在上面一行中,您将general
(仍然不是JSON!)传递给$.post
。
当您传递post
个对象时,jQuery会将其转换为application/x-www-form-urlencoded
编码数据并发送。
如果您想发送JSON,则需要:
这样:
$.ajax({
url: "email2",
method: "POST",
data: JSON.stringify(general),
contentType: "application/json"
});