admin管理员组

文章数量:1334189

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

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

Share Improve this question edited Mar 13, 2012 at 0:42 user1199476 asked Mar 12, 2012 at 23:48 user1199476user1199476 1212 gold badges5 silver badges11 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

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

I had the same need: passing a list of Java objects from Spring boot controller to Javascript code (to be handled as Json objects), I have found a solution:

In Java

Get the list of MyObject, convert it to an equivalent textual Json representation and append it to the model, the result is something like below:

import .google.gson.Gson;

@Service
public class MyService {

    private static final Gson GSON = new Gson();
    
    
    public void getData(final Model model) {
        List<MyObject> myObjectList = getObjects...
        model.addAttribute("myObjectListAsJsonText", GSON.toJson(myObjectList));
    }
    
}

In JSP/HTML page (Not in a separated JS file)

Add a script block to get the Json representation of MyObject list and convert it to a Json array that can be processed by Javascript:

<title>MyApp | Main page</title>
<link rel="shortcut icon" href="resources/img/favicon.ico">
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script  th:inline="javascript">
    var myObjectListAsJson = '${myObjectListAsJsonText}';
    var myObjectJsonArray = JSON.parse(myObjectListAsJson);
</script>

In Any separated Javascipt file of the same page

Can access the global variable myObjectJsonArray that is holding the Json array of MyObject items, like:

function processMyObjectJsonArray() {
    for (var index = 0; index < myObjectJsonArray.length; index++) {
        var myObjectJsonItem = myObjectJsonArray[index];
        console.log("Can access ID attribute of an item of MyObject array:" + myObjectJsonItem.id);
    }
}

本文标签: how to pass json object from java to javascriptStack Overflow