问题:当通过AJAX向MongoDB发送数据时,子目标名称[0] [x]变为单个字符串:“points [0] [x]”。如何防止密钥成为单个字符串?
我使用Ajax这样的帖子在MongoDB中添加了一个对象:
if(errorCount === 0) {
var newDesign = {
filename: 'designs/documents-desktop.jpg',
title: 'Tester',
slug: 'tester',
pos: '1',
points: [
{
x: '0.40',
y: '0.211',
title: 'test',
content: 'Blank for now'
},
{
x: '0.295',
y: '0.090',
title: 'Another Test',
content: 'Blank for now again'
}
]
}
$.ajax({
type: "POST",
data: newDesign,
url: "/data/add-design",
dataType: 'JSON',
}).done(function(response) {
if(response.msg === '') {
} else {
alert("ERROR: " + response.msg);
}
});
}
然后我使用getJSON来获取它,并使用console.log输出this.points [0] [x]:
$.getJSON('/data', function(data) {
$.each(data, function() {
console.log(this.points[0][x])
});
});
但它没有用,我收到了这个错误:
Uncaught TypeError: Cannot read property '0' of undefined
您可以看到当console.log整个对象时,所有数据都存在,但每个子数组键都是一个字符串:
{"_id":"54bcb74584a4c8bd05e3d772","filename":"designs/documents-desktop.jpg","title":"Tester","slug":"tester","pos":"1","points[0][x]":"0.40","points[0][y]":"0.211","points[0][title]":"test","points[0][content]":"Blank for now","points[1][x]":"0.295","points[1][y]":"0.090","points[1][title]":"Another Test","points[1][content]":"Blank for now again"}
您还可以在mongo终端中看到点[0] [x]正在变为单个字符串:
db.filelist.find().pretty();
{
"_id" : ObjectId("54bcc85384a4c8bd05e3d777"),
"filename" : "designs/documents-desktop.jpg",
"title" : "Tester",
"slug" : "tester",
"pos" : "1",
"points[0][x]" : "0.40",
"points[0][y]" : "0.211",
"points[0][title]" : "test",
"points[0][content]" : "Blank for now",
"points[1][x]" : "0.295",
"points[1][y]" : "0.090",
"points[1][title]" : "Another Test",
"points[1][content]" : "Blank for now again"
}
这里有什么我想念的吗?我似乎在NodeJS和Express的服务器端没有任何错误。可能是什么问题?
答案 0 :(得分:0)
感谢@adeneo和@NeilLunn,我们解决了这个问题。 AJAX请求将contentType指定为" json",当它真正需要的是" application / json;字符集= UTF-8&#34 ;.现在,子数组密钥正在MongoDB中正确包含:
$.ajax({
type: "POST",
data: JSON.stringify(newDesign),
url: "/data/add-design",
contentType: 'application/json; charset=utf-8',
}).done(function(response) {
if(response.msg === '') {
} else {
alert("ERROR: " + response.msg);
}
});