我有2个数组用于存储javascript中某些位置的纬度和经度。我想将这两个数组发送到java servlet。我发送JSON字符串是这样的: function saveGeoPts() {
var GeoPts = [
{ "lati" : "18.55" , "longi" : "73.88" },
{ "lati" : "18.67" , "longi" : "73.89" },
{ "lati" : "18.59" , "longi" : "73.99" }, ];
for(var i=0;i<GeoPts.length;i++)
{
//document.write(GeoPts[i].lati+" "+GeoPts[i].longi+" ");
}
// convert JSON to string
var jsonString = JSON.stringify(GeoPts);
document.getElementById('jsonData').value = jsonString;
}</script>
</head>
<body>
<form action="Controller" method="post">
<input type="hidden" id="jsonData" name="jsonData" />
<input type="submit" onclick="saveGeoPts()" >
</form>
</body>
试图以这种方式获取
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.print("in post");
JSONParser parser = new JSONParser();
String jsonString = request.getParameter("jsonData");
try {
JSONObject jsonObject = (JSONObject) parser.parse(jsonString);
System.out.print(jsonObject.get("lati"));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
答案 0 :(得分:0)
从您的问题中,我看到您如何准备数据
var data = JSON.stringify(jsonObject);
我不知道你是怎么发的。我建议你使用jQuery ajax来做这件事。
var GeoPts = [
{ "lati" : "18.55" , "longi" : "73.88" },
{ "lati" : "18.67" , "longi" : "73.89" },
{ "lati" : "18.59" , "longi" : "73.99" }
];
$.ajax({
url: "YOUR_URL",
data: GeoPts,
type: "POST"
}).done(function(response) {
// your logic of success callback
}).error(function(error){
// your logic of error callback
});
如果您希望以这种格式发送到您的服务器数据:“param = 1&amp; paramt = 3 ....”。 你可以用这个:
$.param({param:1 , paramT:3});
// output "param=1¶mT=3"