What is the best method for obtaining a spring controller's object using AJAX?

Here is the AJAX call I am working with:

var url = "UsersGroupReader.html?selectedCompanyName=" + selectedCompanyName + "&test="+Math.random();
req.onreadystatechange = processAccessGroupRequest;
req.open("GET", url, true); 
req.send(null);

function processAccessGroupRequest() {
    if (req.readyState == 4) {
        alert("req.status : " + req.status)
    if (req.status == 200) {
            var message = req.responseXML
            alert("message " + message);
            if (message == "No Database Connection") {
                alert("Please check the database connection");
            } else if (message == "DataDeleted") {
                //alert("Data has been deleted from Database. Please LOGOUT and try again");
                alert("Access Denied");
            } else {
                //setAccessGroups(message);
            }
        }
    }
}

This snippet represents my controller logic

@RequestMapping(value = "Jsp/UsersGroupReader.html", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Vector<String> readUsersGroup(HttpServletRequest request,
        HttpSession httpSession) {
        .....
        .....
        return Vector;

I am currently facing an issue where req.responseXML is returning null

I need assistance in reading the returned vector object in my javascript code. Can someone provide guidance?

Answer №1

To resolve the issue with your Ajax request handling in the controller method, you need to update the return type to match the type of object you want to display in your JSP. This can be a standard class like List<String> or a custom class of your choice.

Additionally, ensure that you include the @ResponseBody annotation in your controller function that handles the request. You will also need to include a JSON library such as jackson-core-asl and jackson-core-mapper version 1.5 to convert your object into a JSON response. Make sure to set the @RequestMapping annotation to

produces=MediaType.APPLICATION_JSON_VALUE
.

Here is an example syntax for the produces attribute:

@RequestMapping(value = "/xxx/yyy", method = RequestMethod.POST, produces=MediaType.APPLICATION_JSON_VALUE)

These changes should help resolve your issue.

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

Align Image According to Dimensions of the Browser

I'm looking for a way to dynamically position an image based on the width and height of the browser within an HTML file. I know that adjusting an image's width/height is possible through code like this: <script> ...

Troubleshooting a Custom Menu Control in HTML

Would you mind taking a look at the menu I have set up in this fiddle: http://jsfiddle.net/Gk_999/mtfhptwo/3 (function ($) { $.fn.menumaker = function (options) { var cssmenu = $(this), settings = $.extend({ title: "Menu", ...

Using Node JS, how to pass a variable length array to a function?

Is there a way to dynamically call an addon function with varying argument lengths? I capture user input in a variable like this: Uinput = [5,3,2]; Now, I want to pass these numbers as arguments to my addon function like this: addon.myaddon(5,3,2); I n ...

Incorporate a directive dynamically within a separate directive

Introducing the table-div directive, which is responsible for rendering both the header and body of a table. Each row within tbody has the option to incorporate additional functionality through a custom directive that can display data linked to its parent ...

What is the best way to implement a "param" feature similar to React's onChange and onClick methods?

I am interested in replicating the functionality of React's onClick, onChange, etc. An example of how React does this is: onClick={(event)=>console.log(event)} My goal is to achieve a similar effect using my custom property: someProp={(wanna_do_t ...

Automatically calculate line total using jQuery when input blurs

Within my interface, I have a section that allows users to input their class information for reimbursement. There are 6 line items available for them to fill out with the cost of books and tuition. Ideally, I would like the user to be able to enter these c ...

Accordion Tuning - The Pro and Cons

Here is a functional accordion that I've implemented, you can view it here This is the JavaScript code I am using: $(document).ready(function ($) { $('#accordion').find('.accordion-toggle').click(function () { //Expa ...

Adjust the divs right element by adding or removing 1 pixel for every size change in the browser

I have been exploring different approaches to achieve this task and it seems like using javascript might be the most effective way. I am currently dealing with a stubborn social icon container placement issue. More details on my previous question can be fo ...

Transfer razor javascript calls in Blazor WebAssembly to a separate class

Scenario Description Greetings, I am currently working on a Blazor WebAssembly project that involves JavaScript interop. Initially, I had this functionality working in a .razor page. However, I now intend to encapsulate and centralize these JavaScript inv ...

Unlock the potential of HTML5 Datalist: A comprehensive guide on integrating it with

The latest version of HTML, HTML5, has introduced a new tag called datalist. This tag, when connected to <input list="datalistID">, allows for autocomplete functionality on web forms. Now the question arises - what is the most efficient approach to ...

Cypress, encountering issues with If/Else or Switch Case implementations

My current challenge involves adding else if / switch case in my test. The issue I am facing is that when the initial 'if' condition fails, it does not go into the else if statement. This problem persists in both else if statements and switch cas ...

The reason why React.js does not automatically bind its functions to the "this" object

I cannot understand the purpose of a function not being bound by this object. In my opinion, all functions should be bound by 'this'. So why doesn't Reactjs automatically set bind(this) by default? For instance, in the code below, if I didn& ...

Trouble concealing tab using slideUp function in Jquery

Whenever I click on the 'a' tag, it displays additional HTML content (list) that is controlled by generic JS code for tabs. However, I want to hide the list when I click on the "Title" link again. What can I do to achieve this? You can view a de ...

The absence of a key is causing an issue - deletion cannot be completed

I need assistance with removing a question after it has been answered, but I am encountering an error message stating that my key is undefined. Error: DELETE http://api/Remove/undefined 400 (Bad Request) state={ qBank:[{id=1,question:'dd',answers ...

Schedule Keeper for ASP.NET MVC

Currently, I am immersed in a project that centers around events. These events will have start dates stored in SQL SERVER through Entity Framework. As part of the frontend design, I aim to emphasize the event dates prominently. My preference is not to util ...

Preserve data across all pages using sessions

On my website, I have a pagination system where each page displays 10 data entries. Whenever a user clicks on the pagination buttons, it triggers a request to the database to fetch the corresponding records. Each data entry also includes a button that can ...

Having trouble retrieving data in Angular from the TypeScript file

demo.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-demo', templateUrl: './demo.component.html', styleUrls: ['./demo.component.css'] }) ...

Exploring the Functionality of Cookies in Nuxt 3 API Endpoints and Middlewares

Can cookies be utilized on the server side in Nuxt 3? For instance, I need to set a cookie in an API and then access its data in middleware: // ~/server/api/testApi.ts export default defineEventHandler(event => { /* setCookie('myCookie', ...

Retrieving component attributes using jQuery or alternate event handlers

In my Angular2 component, I am facing an issue with using vis.js (or jQuery) click events. Despite successfully displaying my graph and catching click events, I encounter a problem where I lose access to my component's properties within the context of ...

Launch the desired div in a fancybox from a separate webpage

i have a table with links to another html doc like this <div id="gallery_box"> <ul> <li> <a href="http://www.geestkracht.com" target="_blank"><img src="images/gallery/Geestkracht.jpg" alt="G ...