Acquire JSON data from a Spring MVC controller using JavaScript

I am looking to retrieve JSON data from a Spring controller using JavaScript. Below is the REST API call that returns the JSON data:

{id: '0', item: [
    {
        id: 'all',
        text: 'ALL',
        item: [
            {
                id: 'all-',
                text: 'ALL-',
                item: [
                    {
                        id: 'Market1-0',
                        text: 'Market1',
                        item: [
                            {
                                id: 'id2',
                                text: 'Project 2'
                            },
                            {
                                id: 'id1',
                                text: 'Project 1'
                            }
                        ]
                    }
                ]
            }
        ]
    }
]
}

Here is the code for the Spring handler:

public class DashboardHandler {

public String getProjects() throws ParseException{

    SimpleClientHttpRequestFactory rf = new SimpleClientHttpRequestFactory();
    rf.setReadTimeout(50000);
    rf.setConnectTimeout(50000);

    RestTemplate restTemplate = new RestTemplate(rf);
    String page = restTemplate.getForObject(
            "http://localhost:9090/mcps/api/v1.0/user/2/projects",
            String.class);

    // Parsing the JSON response
    JSONParser parser = new JSONParser();
    JSONObject customerListObject = (JSONObject) parser.parse(page);
    
    // Building the JSON object
    StringBuilder builder = new StringBuilder();
    builder.append("{id:'0', item:[");
    builder.append("{id:'all', text:'ALL', item:[");
    int i=0;
    for (Object customer : customerListObject.keySet()) {
        JSONObject customerJsonObject = (JSONObject) customerListObject
                .get(customer.toString());
        for (Object region : customerJsonObject.keySet()) {
            JSONObject marketJsonObject = (JSONObject) customerJsonObject
                    .get(region.toString());
            for (Object market : marketJsonObject.keySet()) {
                builder.append("{id:'"+market+"-"+i+"', text:'"+market+"', item:[");
                i++;
                JSONObject projectObject = (JSONObject) marketJsonObject
                        .get(market.toString());
                for(Object projectId:projectObject.keySet()){
                    JSONObject projectJsonObject = (JSONObject) projectObject.get(projectId);
                    for(Object project: projectJsonObject.keySet()){
                        builder.append("{id:'"+projectId+"', text:'"+project+"'},");
                    }
                }

                builder.append("]},");
            }

        }
    }
    builder.append("]}]}");
    
    return builder.toString();
}

}

The controller with request mapping URL is as follows:

@Controller
public class DashboardController {

@RequestMapping(value = "/getProjects", method = RequestMethod.GET)
public @ResponseBody String getProjects(HttpServletRequest request) {
    DashboardHandler dashBoardHandler = new DashboardHandler();
    try {
        return dashBoardHandler.getProjects();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

}

Now, I want to know how to access the /getProjects URL in JavaScript. Can anyone help me with this?

Answer №1

Utilizing ajax is the recommended approach

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">

<script type="text/javascript">
$.ajax({
type : 'GET',
url : '${pageContext.request.contextPath}/getProjects',
success : function(data) {
//parse json data
alert(data.id);
$('#mydiv').append(data.id);
//data.id is 0
//data.item[0].id is 'all'
//data.item[0].text is 'ALL'
//data.item[0].item[0].id is 'all-'
//data.item[0].item[0].text is 'ALL-'
//data.item[0].item[0].item[0].id is 'Market1-0'
//data.item[0].item[0].item[0].text is 'Market1'
}
});
</script>
</head>
<body>
<div id='mydiv'>Hello</div>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing a nested function before moving on to the subsequent code statements

I have a requirement where certain functions in my codebase need to check if a user is logged in before proceeding. Instead of duplicating this check logic, I want to call a single getUser() function each time. Here is the order of operations for the func ...

"Troubleshooting: Why is the guildMemberAdd event in Discord.js not

I'm currently in the process of creating a Discord bot for my personal server using Discord.js and following the discord.js guide. However, I've run into an issue with my event handler. When I add a file for another event, the code within that m ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

See-through Windows on Linux (Electron)

When creating a new BrowserWindow in Electron and using the transparent argument set to true, it typically gives the window a transparent background. However, I have found that this is not the case for Linux based on my knowledge. I have also attempted to ...

Using the jQuery each function to iterate through a menu

Hi everyone, I have a menu and I'm trying to add a toggle animation to each parent menu. However, I'm currently stuck because when I click on a parent menu, all parent menus show their child menus at once. I think I may need to use the jQuery &ap ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Extract data from XML and display the findings

Currently delving into the world of PHP, I find myself facing a challenge with one of my scripts. I'm working on fetching an XML file and displaying the results on the page. However, I am only interested in the rows where the refTypeID is equal to 10, ...

Vue.js: Why Objects are Returning 'Undefined' Values in Arrays

Attempting to improve my JavaScript OOP skills, I am also delving into learning vue.js. My current project involves creating a simple task list for practice purposes. While most of it is complete, I have hit a roadblock with the remove task function. Initi ...

Refresh the data table following the submission of a form

I've been looking around, but I haven't found a solution that works for me. I have a datatable with an edit button in one of the columns. When a user clicks on the edit button, a modal pops up allowing them to change an entry in the datatable. Af ...

Custom attribute with ng-options in AngularJS

I am currently working with the following directive in my select. ng-options="option.value as option.title for option in exportTypes" The array $scope.exportTypes contains objects with attributes title, value, and generatesFile. I would like to include t ...

"Using jQuery's animate() function to dynamically change text content

I'm currently venturing into the world of jQuery animate() and decided to create a presentation-style project for practice. However, I've hit a roadblock when attempting to alter the text within my div element in the midst of an animation utilizi ...

Tips for setting parameter values using the <input> tag

Currently facing an issue with javascript in html. I have created a function with two parameters and would like to pass values to them using an input tag, instead of directly inside the code when the function is invoked. I initially followed the tradition ...

Finding results in AngularJS by typing at least 4 characters into the input field

I am using a MySQL database to search with AngularJS. How can I set it up so that the search only triggers when at least 4 characters are inputted? Here is the HTML code: <div class="search"> <form action="" method="post" class="searchform" &g ...

Angular state correctly maps to the controller but is not reflected in the HTML

I'm currently in the process of setting up a basic Angular application, something I've done many times before. I have defined a home state and another state for a note-taking app, but I am facing an issue where neither state is displaying or inje ...

The performance of Jquery Animate is acting strangely after the upgrade to version 1.11

Take a look at http://jsfiddle.net/integerz/k19x8L1b/2/ which uses version 1.7.x $(function () { $("#clickme").toggle(function () { $(this).parent().animate({right:'0px'}); }, function () { $(this).parent().animate({righ ...

Automatically navigate to a specific selection within the Autocomplete feature

Imagine having a dropdown or Autocomplete list in Material-UI with a long list of items. How can you make the list automatically scroll to a specific item when you open the dropdown? For instance, if we take the list of top100Films, the initial displayed i ...

Modifying webpage code

I am looking to develop a system where I can edit various elements such as the navbar, paragraphs, and images directly from a web page. I understand that this can be achieved with JavaScript, but I am facing the issue of my customizations reverting to defa ...

Unusual quirks in javascript variables when used with arrays

Unsure if this question has been asked previously. Nevertheless, I couldn't find it anywhere. I've observed a peculiar behavior that seems to occur only with arrays. Here is the typical behavior I anticipate from variables: var k = 10, m = ...

Filter documents by matching arrays of objects using MongoDB Aggregation

I am dealing with documents that contain arrays of nested objects. Some fields have been omitted for simplicity. Here is an example of how the documents are structured (2 documents): { title: 'abc', parts: [ { part: "verse&quo ...

Differences between CookieParser and req.cookies in ExpressJS

As I was reading the documentation on req.cookies in expressjs docs, I learned that when the cookieParser() middleware is used, this object defaults to {} but otherwise contains the cookies sent by the user-agent. Then, exploring the details of the Coo ...