How to pass objects from Java to JavaScript using JSON?
A while back I 开发者_运维知识库was given the answer of using JSON to pass things from my application to JavaScript. What I don't understand is how I actually pass the object to JavaScript I see that you have to use a .json file.
And then what? I am able to convert my Java objects to JSON objects but it's passing that I can't get my head around. I am using JSP and Servlets to write my application.
The file extension .json
is not so relevant. It's just all about the HTTP Content Type header. As long as it's application/json
, the webbrowser knows perfectly what to do with it. In terms of JSP/Servlet you basically need to create a servlet class which listens on a certain url-pattern
, processes the request parameters or pathinfo accordingly and writes a JSON string to the response in the doGet()
method.
Here's a fictive example of a servlet which returns city option value/label pairs based on the selected value of a country dropdown, it uses Google Gson to convert fullworthy Java objects to JSON in an oneliner:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String country = request.getParameter("country");
Map<String, String> cities = cityDAO.find(country);
String json = new Gson().toJson(cities);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
Map such a servlet on an url-pattern
of /cities
in web.xml
(or if you want a bit more SEO friendly approach, map it on /cities/*
and use request.getPathInfo()
instead).
Finally, in the JS code which is executed during onchange of a country dropdown, you just let it fire an asynchronous (ajaxical) request on this servlet with the selected country as parameter (or pathinfo). I'll give a jQuery based example since it insanely eases firing ajax requests and traversing/manipulating HTML DOM (the "raw" JS code would otherwise have been up to 5 times as long).
$(document).ready(function() {
$('#country').change(function() {
var selectedCountry = $(this).val();
var servletUrl = 'cities?country=' + selectedCountry;
$.getJSON(servletUrl, function(options) {
var city = $('#city');
$('>option', city).remove(); // Clean old options first.
if (options) {
$.each(options, function(value, label) {
dropdown2.append($('<option/>').val(value).text(label));
});
} else {
dropdown2.append($('<option/>').text("Please select country"));
}
});
});
});
Here is the appropriate HTML example of the JSP:
<select id="country" name="country">
<c:forEach items="${countries}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
<select id="city" name="city">
<option>Please select country</option>
</select>
(assuming that ${countries}
is an Map<String, String>
in application scope)
Hope this clears the one and other :)
See also:
- Related questions with tags
[json]+[jsp]
. - Related questions with tags
[json]+[servlets]
.
JSON is basically a Javascript object storage format. So, it's native to Javascript.
Loading a JSON File
You could load a JSON file when your webpage is loaded like this, just like any .js file:
<html>
<head>
<script type="text/javascript" src="myfile.json"></script>
</head>
—clipped—
It is also important to have a callback function, or a function that's called when the JSON has loaded. For example, the contents of "myfile.json" should read:
anz([arbitrary JSON here]);
where anz()
is defined somewhere as:
function anz(JSONdata) {
//process data here
}
JSON can also be dynamically loaded, or loaded after the page has rendered/loaded.
Getting Data From a JSON File
So, once you have a JSON file that is somehow loaded, and calls your callback function with the JSON data, you can read it — just like any other Javascript Object.
If this was passed to your callback function…
{"data":{"user_name":"Joe", "user_id":"97304239042", "user_rank":3}}
… To get the user's name:
function anz(JSONdata) {
var userName = JSONdata.data.user_name;
// userName returns "Joe"
}
精彩评论