简体   繁体   中英

how to pass json object from java to javascript?

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?

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:

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

in my jsp file I have:

<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.

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

<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:)

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

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:

Spring Controller:

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

JSP :

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

given, that the Coordinate class 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 Jackson , and the ContentNegotiatingViewResolver .

Take a look at: 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM