如何将json对象从java传递给javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9676423/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:01:00  来源:igfitidea点击:

how to pass json object from java to javascript?

javajavascriptjsonspring

提问by user1199476

I'm trying to pass data from spring controller to javascript but with no luck. Should I use ajax to do this? Please could you give me some hints on how do this? What is the best way?

我正在尝试将数据从 spring 控制器传递给 javascript,但没有运气。我应该使用ajax来做到这一点吗?请你能给我一些关于如何做到这一点的提示吗?什么是最好的方法?

In my controller I try to pass data:

在我的控制器中,我尝试传递数据:

@RequestMapping(value = "/map", method = RequestMethod.GET)
public String map(ModelMap model) {

...

model.addAttribute("trackpoints", json);


return "map";

}

where json is a gson object (JsonObject) containing:

其中 json 是一个 gson 对象 (JsonObject),其中包含:

{"trackpoints":[{"latitude":52.390556,"longitude":16.920295},
{"latitude":52.390606,"longitude":16.920262}]}

in my jsp file I have:

在我的jsp文件中,我有:

<script type="text/javascript">

var myJSON = {};

myJSON = ${trackpoints};

document.writeln(myJSON.trackpoints);

</script>

but the result is:

但结果是:

[object Object],[object Object]

I explain this in more detail: >

我更详细地解释了这一点:>

i want use google maps api to display map and draw path coordinated from many lat,longs. i reckon json will be better than list, but i can be wrong.

我想使用谷歌地图 api 来显示地图并绘制从许多经纬度协调的路径。我认为 json 会比列表更好,但我可能是错的。

i try to adjust code from documentation - in code below i try to replace hardcoded coordinates with loop, and values from json object.

我尝试从文档中调整代码 - 在下面的代码中,我尝试用循环替换硬编码坐标,以及来自 json 对象的值。

<script type="text/javascript">
function initialize() {
    var myLatLng = new google.maps.LatLng(0, -180);
    var myOptions = {
        zoom : 3,
        center : myLatLng,
        mapTypeId : google.maps.MapTypeId.TERRAIN
    };

    var map = new google.maps.Map(document.getElementById("map_canvas"),
            myOptions);
    var flightPlanCoordinates = [
            new google.maps.LatLng(37.772323, -122.214897),
            new google.maps.LatLng(21.291982, -157.821856),
            new google.maps.LatLng(-18.142599, 178.431),
            new google.maps.LatLng(-27.46758, 153.027892) ];
    var flightPath = new google.maps.Polyline({
        path : flightPlanCoordinates,
        strokeColor : "#FF0000",
        strokeOpacity : 1.0,
        strokeWeight : 2
    });

    flightPath.setMap(map);
}
</script>

i hope it's now more clear:)

我希望现在更清楚了:)

回答by jabu.10245

myJSON.trackpointsis an array of two objects. If you want to write it as HTML you could do something like this:

myJSON.trackpoints是两个对象的数组。如果你想把它写成 HTML,你可以这样做:

function writeCoordinates(coords) {
    document.writeln('<div>lat = ' + coords.latitude);
    document.writeln(', lon = ' + coords.longitude + '</div>');
}

int len = myJSON.trackpoints.length;
for (int i = 0; i < len; i++) {
    writeCoordinates(myJSON.trackpoints[i]);
}

BTW: JSON is really useful when you're using AJAX requests, but for "normal" requests it's better to put plain Java objects into the model, for example:

顺便说一句:当您使用 AJAX 请求时,JSON 非常有用,但对于“普通”请求,最好将普通 Java 对象放入模型中,例如:

Spring Controller:

弹簧控制器:

List<Coordinate> trackpoints = ...
model.addAttribute("trackpoints", trackpoints);

JSP:

JSP:

<c:forEach items="${trackpoints}" var="coord">
    <div>lat = ${coord.latitude}, lon = ${coord.longitude}</div>
</c:forEach>

given, that the Coordinateclass has the methods getLatitude()and getLongitude(). That method in the Spring controller can even be used for both "normal" and AJAX requests, by using a JSON encoder, like Hymanson, and the ContentNegotiatingViewResolver.

给定,Coordinate该类具有方法getLatitude()getLongitude()。通过使用 JSON 编码器(如Hymanson)和ContentNegotiatingViewResolver,Spring 控制器中的该方法甚至可以用于“普通”和 AJAX 请求。

回答by Jeff Woodard

Take a look at: http://jsfiddle.net/AHue8/4/

看看:http: //jsfiddle.net/AHue8/4/

I guess the take-away here is that you need to specify which element in the trackpoint object you want and you countrol how those are displayed in the browser. Since a "trackPoint" isn't a primitive data type (it's an object with 2 data elements latitude and longitude), the browser doesn't know how to interpret it, so you have to tell it how.

我想这里的要点是您需要指定您想要的 trackpoint 对象中的哪个元素,并计算这些元素在浏览器中的显示方式。由于“trackPoint”不是原始数据类型(它是具有 2 个数据元素纬度和经度的对象),浏览器不知道如何解释它,因此您必须告诉它如何解释。