将JSON字符串发布到JSP时出错意外令牌

时间:2014-01-27 14:47:16

标签: javascript ajax json jsp post

这是我的代码:

var polylineStringified = JSON.stringify(polyPath.getArray());

$.ajax({
        type: 'POST',
        url: 'jsonposttest.jsp',
        data: { Polyline: polylineStringified },
        dataType: 'json',
        success: function(json) {
            alert('json from post test: ' + JSON.stringify(json));
        }, error: function(xhr, ajaxOptions, thrownError){ 
             alert('Error xhr : ' + xhr.status); 
            alert('Error thrown error: ' + thrownError); 
        }

});

服务器端:

<%

String test;
test = getRequest(pageContext, "Polyline");

response.setContentType("application/json");

%>

[
 {"val": "Got it: <%=test%>" }
]

polylineStringified看起来像这样:

[{"d":41.919372021888826,"e":-87.69811456091702},{"d":41.90506457136218,"e":-87.23119561560452},{"d":41.80277524389252,"e":-87.23668877966702},{"d":41.74747099702249,"e":-87.35479180701077}]

我在控制台中遇到的错误是意外的令牌d。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我认为你不必要地对你的javascript对象进行字符串化。如果您使用以下内容会发生什么?

var polylineArray = [{
    "d": 41.919372021888826,
    "e": -87.69811456091702
}, {
    "d": 41.90506457136218,
    "e": -87.23119561560452
}, {
    "d": 41.80277524389252,
    "e": -87.23668877966702
}, {
    "d": 41.74747099702249,
    "e": -87.35479180701077
}];

$.ajax({
        type: 'POST',
        url: 'jsonposttest.jsp',
        data: { Polyline: polylineArray },
        dataType: 'json',
        success: function(json) {
            alert('json from post test: ' + JSON.stringify(json));
        }, error: function(xhr, ajaxOptions, thrownError){ 
             alert('Error xhr : ' + xhr.status); 
            alert('Error thrown error: ' + thrownError); 
        }
});

编辑:这是另一个例子,您可以在jsFiddle尝试。

它应该非常简单,因此您可以在每一步将其与您的产品进行比较,以找出您的情况有什么问题。

jQuery(document).ready(function ($) {
    var Q = function (d, e) {
        this.d = d;
        this.e = e;
    }
    var data = [];
    for (var i = 0; i < 5; i++) {
        var r1 = 100 * (2*Math.random() - 1);
        var r2 = 100 * (2*Math.random() - 1);
        data.push(new Q(r1, r2));
    }
    console.log("About to send data", data);

    $.ajax({
        type: 'POST',
        url: '/echo/json/',
        data: {
            Polyline: data
        },
        dataType: 'json',
        //processData: false,
        success: function (data, textStatus, jqXHR) {
            console.log("success", data, textStatus, jqXHR);
            //alert('json from post test: ' + JSON.stringify(data));
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log("error", xhr, ajaxOptions, thrownError);            
            //alert('Error xhr : ' + xhr.status);
            //alert('Error thrown error: ' + thrownError);
        }
    });
});
相关问题