1

I have below sample map arraylist. First, how do i access this arraylist from inside a pure html using javascript? Second, how do i iterate over this list?

<%@page import="org.json.simple.JSONObject"%>
<%@page import="org.json.simple.JSONArray"%>
<%
JSONObject json = new JSONObject();
JSONArray  list = new JSONArray();
JSONObject course1,course2,course3,course4,course5;

course1 = new JSONObject();
course1.put("code", "ME101");
course1.put("desc", "Marine Engineering 101");
course1.put("sched", "June 1 - August 30, 2014");
course1.put("rsvd", "56");
course1.put("crssched", "cme101s1");
list.add(course1);
course2 = new JSONObject();
course2.put("code", "ME102");
course2.put("desc", "Marine Engineering 102");
course2.put("sched", "September 1 - November 31, 2014");
course2.put("rsvd", "25");
course2.put("crssched", "cme102s1");
list.add(course2);
course3 = new JSONObject();
course3.put("code", "CS101");
course3.put("desc", "Certificate on Seamanship 101");
course3.put("sched", "June 1 - June 30, 2014");
course3.put("rsvd", "36");
course3.put("crssched", "ccs101s1");
list.add(course3);
course4 = new JSONObject();
course4.put("code", "ME201");
course4.put("desc", "Marine Engineering 201");
course4.put("sched", "June 15 - July 16, 2014");
course4.put("rsvd", "65");
course4.put("crssched", "cme201s1");
list.add(course4);
course5 = new JSONObject();
course5.put("code", "ME202");
course5.put("desc", "Marine Engineering 202");
course5.put("sched", "July 1 - August 30, 2014");
course5.put("rsvd", "15");
course5.put("crssched", "cme202s1");
list.add(course5);

json.put("Courses", list);
response.setContentType("application/json");
response.getWriter().write(json.toString());

The scenario is that i have html-only files in the webserver and i get data from jsp files on another server which i need to display in a table to the html files using javascript or jquery.

Any ideas?

EDIT

Based on user13500's suggestion, I have looked into JSON and updated the sample data above. Tested it to write on the page and it does print out the key value pairs.

How do I now "expose" the json object and access it from another html page?

10
  • 1
    List<Map<String, String>> list isn't Javascript. Commented Feb 22, 2014 at 8:13
  • No it's not. It's a "sample" data from jsp. Commented Feb 22, 2014 at 8:16
  • @JNewbie: Also note that from your updated code that would serve an object holding an array holding objects, not an array holding objects. And: as you send the "application/json" header as well, the return on the ajax request will not be a string but the object. (So no JSON.parse(reply) in Javascript.) Commented Feb 22, 2014 at 12:17
  • If you want the array say list.toString() instead of json.put("Courses", list); and json.toString() Commented Feb 22, 2014 at 12:20
  • In javascript you could add an if (typeof responseData === "string") { responseData = JSON.parse(responseData); } Commented Feb 22, 2014 at 12:25

1 Answer 1

0

Looks like you might want to look into JSON.

In effect deliver something like this from JSP (Without the formatting):

...
}, {
  "code"     : "ME201",
  "desc"     : "Marine Engineering 201",
  "sched"    : "June 1 - June 30, 2014",
  "rsvd"     : "65",
  "crssched" : "cme201s1"
} , {
  "code"     : "ME202",
  "desc"     : "Marine Engineering 202",
  "sched"    : "June 1 - June 30, 2014",
  "rsvd"     : "65",
  "crssched" : "cme202s1"
}
...

In Javascript you could then do JSON.parse() and access the array objects by iteration etc.

var i, obj, objArray = JSON.parse(json_from_JSP);

for (i = 0; i < objArray,length; ++i) {
    obj = objArray[i];
    // Here you would have e.g. obj.code === "ME201"
    // or you can access it by obj["code"] 
    // or objArray[i]["code"] etc.
}

In your HTML document you could include JSON script, if your target audience is wide and might not have JSON support in their browser, directly form you own server or by linking in from for example cdnjs. (Search "json" – json2 should suffice.)


Edit as per your comment and update:

To get the data from the server. You either output it directly into the document by script embedding, typically:

var jsonData = '<%= json.toString() %>';

In this case, as you want to get the data by request on an already rendered page, you use Ajax request. As you use jQuery a simple example would be:

HTM:

<!DOCTYPE html>
<html>
<head>
<title>JSP Ajax test</title>
<meta charset="UTF-8" />
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id="btn_data">Get data</button>
<pre id="dump"></pre>
</body>
</html>

Javascript:

// Function to process the data in response
function process_json(jsonString) {
    var i, obj, data = JSON.parse(jsonString);
        dump = $("#dump");

    // If you want to see what the data string looks like
    dump.html(jsonString + "\n");

    // Loop the array and do what you want with each object.
    for (i = 0; i < data.length; ++i) {
        $("#dump").append("CODE: " + data[i].code + "\n");
    }
}

$(document).ready(function () {
    $("#btn_data").click(function () {
        $.ajax({
            type    : "GET",
            url     : "schedules.jsp",
            async   : false,
            success: process_json // Function to process the data
        });
    });
});

A bit more readable dump:

You can also have a pretty-print function while you play with this, example:

function pretty_print(jsonString) {
    var obj = JSON.parse(jsonString),
        str = JSON.stringify(obj, null, "    ");
    $("#dump").html(str + "\n--------------------------\n");
}

Look at ajax requests. Either in use with jQuery or in pure Javascript. You can also extend it to include POST and GET data that you would further process on your server. Typically making targeted requests filtering out what you want in return.


Sample output:

With the above + pretty_print() your output should be something like:

+------------+
|  Get data  |   <--- button ;-)
+------------+


[
    {
        "code": "ME201",
        "desc": "Marine Engineering 201",
        "sched": "June 1 - June 30, 2014",
        "rsvd": "65",
        "crssched": "cme201s1"
    },
    {
        "code": "ME202",
        "desc": "Marine Engineering 202",
        "sched": "June 1 - June 30, 2014",
        "rsvd": "65",
        "crssched": "cme202s1"
    }
]
--------------------------
CODE: ME201
CODE: ME202
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks! I looked into JSON and have updated the sample data above. How do I "expose" it to be able to access it via javascript from another html page?
@JNewbie: Do I read you correctly if I say your JSP script is not part of the code serving the HTML, but a backend script that you want to "call" to get the JSON data/map array?
Yes, you are correct. I need to call a jsp file (schedules.jsp) which would contain this JSON map array, from inside a html file (viewschedules.html).
I really appreciate you taking the time to help me with this problem. I have it working now because of the solution you provided. I'll give you +1 if I could now but I still can't. Thank you very much!
@JNewbie: You are very welcome. You also show effort in responding and taking interest, which is a big plus. The use of AJAX + JSON in combination with some server language and Javascript is very powerful and makes for some rather nifty possibilities when it comes to dynamic content. There is a lot of good Q/A's here on SO on the subject. Also check out the stackoverflow.com/tags/javascript/info tag page, esp. Learning JavaScript section (if you are new to Javascript.) Read/skim the ECMA standard if you are very interested. I also recommend this: webplatform.org
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.