我在这里有点困惑,我正在尝试使用以下代码将数据发布到我的节点 js 服务器:
$.ajax({type:'POST',
url:'/map',
data:'type=line&geometry='+str,
success:function(msg)
{
console.log(msg);
},
datatype:'json'
});
这是这里的结果:
{ type: 'line', geometry: 'b~cqCge{b[mv|q@xnyC' }
这不是 JSON。我之前曾尝试使用 contentType
并这样做:
$.ajax({type:'POST',
url:'/map',
data:{type:'line',geometry:str},
success:function(msg)
{
console.log(msg);
},
datatype:'json',
contentType:"application/json"
});
即使这样发送的数据也没有任何变化。我也尝试过使用第一个数据字符串的上述方法。我也尝试过将 processData
设置为 false
以及代码块中的方法。
对我来说数据在 JSON
中并使用 AJAX
很重要,因为我正在尝试 insert into mongodb from node js using mongojs and it fails
最佳答案
实际上 dataType
与输入无关,而与输出有关。
相反,您想要的是将输入的 data
字符串化,然后将其作为单个变量发送到后端,后端可以对其进行解码:
$.ajax({type:'POST',
url:'/map',
data: {data: JSON.stringify({type: 'line', geometry: str})},
success:function(msg)
{
console.log(msg);
},
dataType:'json'
});
这样在您的后端您只需解码数据
,它现在应该是一个来自 JSON 的功能齐全的对象。
请注意,为此您需要 JSON 类,JQuery 默认不包含此功能:https://github.com/douglascrockford/JSON-js
关于javascript - jQuery 不在 AJAX POST 请求上发送 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22372597/