Sending a JSON object from JSP to JavaScript using AJAX

Is there a way to transfer JSON values from JSP to JavaScript as an object using AJAX without resorting to global JavaScript variables, which can expose the JSON content in the page's source?

The desired scenario is as follows:

  • The JSP URL is opened in a browser.
  • Data is generated within a scriptlet and converted to JSON format
  • The JSON object is then passed to JavaScript

Based on the scenario above, it seems that JavaScript needs to trigger the AJAX call to the JSP. However, this approach will result in the JSP code being executed twice:

  • When the page loads - data preparation occurs
  • On each subsequent AJAX call, the same code will run again

Unfortunately, there are several constraints: no jQuery, no other libraries, no servlets, and no additional JSPs. :(

EDIT:

There is another complication: I need to pass multiple JSON objects to JavaScript, and using response.getWriter().write(); won't suffice.

Merging all JSON objects into one string for transmission doesn't seem like the best solution.

The parsing of the response object in JavaScript http.responseText could become unmanageable.

Answer №1

Is there a need for ajax in this situation? If you are aware that you must load certain data from the server onto a JSP page, you can achieve that using scriptlets directly:

For example:

<%@ page import="com.mypackage.PersonDAO" %>
<html>
<body>
<table>
<th>Name</th><th>Email</th><th>Contact</th>

<%
List<Person> myList = PersonDAO.getAllPersons();
for(Person person:myList)
{ 

%>
<tr>
<td><%=person.getName()%></td>
<td><%=person.getEmail()%></td>
<td><%=person.getContact()%></td>
</tr>
<%}%>
</table>
</body>
</html>

This is just a basic example. More advanced tasks can be accomplished using JSTL.

Therefore, no jQuery, servlets, ajax, or additional JSP pages are necessary :)

UPDATE

If you require data in your JavaScript before the page loads, you can utilize jQuery's holdReady() method.

$.holdReady( true );
$.get( url, function() {
// Perform something
$.holdReady( false );
});

However, remember that modern browsers come equipped with developer tools like Firebug for Mozilla, which can capture any ajax calls made. To enhance security, consider encrypting the calls though it may add complexity. If you provide more details about your implementation scenario, I can offer further suggestions.

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

Sending data from an HTML textarea to a PHP variable without user input

After spending more than two days searching for a solution to this problem, I am now reaching out directly with my question. Although there have been some hints and partial answers, nothing has definitively resolved the issue I am facing, prompting me to m ...

Challenges regarding OAuth2 and the angular-auth2-oidc Library - Utilizing PKCE Code Flow

As a newcomer to OAuth2 and the angular-auth2-oidc library, I may make some beginner mistakes, so please bear with me. MY GOAL: I aim to have a user click on the login link on the home page, be directed to the provider's site to log in, and then retu ...

Implementing React router for dynamic page rendering

I'm struggling to make sense of a particular piece of code. Can someone provide an explanation? I'm particularly confused about the role of "props" in this section and how it is essential for the code to work correctly. If I remove "props," my co ...

Is there a way to sort search outcomes by a drop-down menu in Next.js?

I am currently working on implementing a filter for my data based on selections made in a drop-down menu. Here's the setup: I have MSSQL data being pulled into NextJS using Prisma (ORM). My goal is to create a dropdown filter that will refine the di ...

Every item in my array is replaced by the most recently added element

Take a look at this code snippet on JSFiddle: https://jsfiddle.net/reko91/998woow6/ The issue I am facing with my project is that every time I add an element to an array, it ends up overwriting all the existing elements with the newly added one. To repli ...

I am looking to manage the error handling service, and my next step is to intentionally insert a single error into my service and have it automated

Need help with error handling in my service. I want to manually insert a single error, but would like it to be done automatically instead. 'use strict'; angular.module('nexoolApp.errorservice', ['nexoolApp.config']) .servic ...

Abort an ajax request if it is taking too long to finish

On my website, I have implemented a search feature that queries my database using Ajax and displays the results in a modal box upon successful completion. The modal is then shown once the results are loaded. My backend is powered by Django. Is there a me ...

I am experiencing an issue where the Laravel URL is not being passed to the controller

In my project, I am utilizing ajax along with Laravel 5.4. The issue I am facing is that when the ajax function is executed, it successfully returns the email but does not display the URL page in the console window. Here is the code for the Ajax function: ...

Resizing images using a dynamic frame size

I am in need of some assistance as I am currently facing a roadblock. My goal is to develop a picture framing tool for photos where users can specify the size of their photo, choose a colored cardboard mount, and select a frame type. My client has requeste ...

Dynamic sidebar that adheres to the content and is placed alongside it using JavaScript

I am in need of creating a sticky sidebar that will float beside my content column. The purpose of this sidebar is to contain jump links on the page, similar to what can be seen on this page, but with the navigation buttons positioned directly next to the ...

The z-index overlapping problem in webkit browsers is a result of Angular 7 animations

I have implemented staggered animations in my Angular 7 application to bring elements to life upon page load. However, I am facing a strange z-index problem with one of my components. Here is the animation code: @Component({ selector: 'track-page& ...

Internet Explorer experiencing problems with JSON when using ajax请求

After struggling with this issue for a significant amount of time, I have decided to seek help from the community. I am utilizing Google Custom Search REST API in combination with jQuery to retrieve results and display them in the browser. The problem I a ...

What is the best way to combine an array of objects into a single object in typescript?

Looking for some help with converting an array of objects into a single object using TypeScript. Here's the structure of the array: myArray = [ {itemOneKey: 'itemOneValue', itemTwoKey: 'itemTwoValue'}, {itemThreeKey: ' ...

What sets apart the float and integer data types when they share the same size?

Is there a distinction between the float and integer data types if their sizes are equal? ...

Interactive calendar feature with a popup that appears when hovering over an event

I am looking to create a popup on hover with full calendar functionality, similar to the one seen at this link. I have attempted using full calendar with qtip, but I was unable to achieve a clickable popup as it disappears when the mouse moves away. Here ...

I need assistance with this ajax/javascript/php

I am currently working on creating a dynamic chained list. The idea is to have the user make selections from the first four dropdown lists, and based on their choices, a fifth dropdown list should appear. However, I am facing some issues with my code as th ...

Adding CSS styles to an HTML page using JavaScript

Unfortunately, I do not have the ability to access the HTML directly as it is generated dynamically by a program. However, I do have access to the JS page that is linked to it. As an example, I am able to manipulate elements using JavaScript like so: ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

PHP Object-Oriented Programming Issue with PDO and AJAX

I am currently working with PHP OOP and PDO connection. I need assistance on how to call a function from a class using AJAX. For instance, let's say I want to call the printBooks function through AJAX. Class - Entity Book: class Book{ privat ...

Utilizing Material-UI Select for creating a number range dynamically

Seeking a solution to create a select element using material-ui that offers a range of numbers from 0 to 20,000,000 in increments of 25,000. Currently, I have accomplished this using a for loop. for (let price = 0; price <= 20000000; price = price + 250 ...