我正在开发node.js,express.js和mongodb上的应用程序。我的任务是将数组传递给服务器端并将其插入到db。我在整个网络中搜索过,发现我需要通过JSON.stringify()对我的数组进行字符串化,但是当我在服务器端对它进行控制时,它看起来很奇怪,每次使用JSON.parse()的尝试都以错误结束。 这是一个通过JSON.stringify()传递的数组:
[{
"city": "London",
"date": "20.11.2015",
"sector": "A",
"row": "1",
"place": "1"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "A",
"row": "1",
"place": "2"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "A",
"row": "2",
"place": "1"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "A",
"row": "2",
"place": "2"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "B",
"row": "1",
"place": "1"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "B",
"row": "1",
"place": "2"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "B",
"row": "2",
"place": "1"
}, {
"city": "London",
"date": "20.11.2015",
"sector": "B",
"row": "2",
"place": "2"
}]
当我将它传递给服务器端时,它看起来像这样:
{ '[{"city":"London","date":"20.11.2015","sector":"A","row":"1","place":"1"},{"city":"London","date":"20.11.2015","sector":"A","row":"1","place":"2"},{"city":"London","date":"20.11.2015","sector":"A","row":"2","place":"1"},{"city":"London","date":"20.11.2015","sector":"A","row":"2","place":"2"},{"city":"London","date":"20.11.2015","sector":"B","row":"1","place":"1"},{"city":"London","date":"20.11.2015","sector":"B","row":"1","place":"2"},{"city":"London","date":"20.11.2015","sector":"B","row":"2","place":"1"},{"city":"London","date":"20.11.2015","sector":"B","row":"2","place":"2"}]': ''}
并且任何解析它的尝试都会导致500错误。那么我做错了什么?
答案 0 :(得分:4)
你看到它在做什么吗?它使用您传递的JSON作为没有值的键。
你可以做到
$.ajax({
method: "POST",
url: "/tickets/addticket",
dataType: "json",
data : { val : JSON.stringify(dataToSend) }
}
并且node.js读取val
的查询字符串值其他选项是设置内容类型
$.ajax({
url: "/tickets/addticket",
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(dataToSend)}
);