transferring data from grails to javascript via a map

I am facing an issue with passing a Map object from my Grails controller to JavaScript. The code snippet in my controller is as follows:

def scoreValue = new HashMap<String,String>();
scoreValue.put("0","poor");
scoreValue.put("1","good");
...

return (view:'viewname', model:[scoreValue:scoreValue]);

I have been searching for a solution and came across this link pass a groovy array to javascript code, but it did not resolve my problem.

To try and solve the issue, I modified the return statement to

return (view:'viewname', model:[scoreValue:scoreValue as grails.converters.JSON])
and then inside my GSP view, I used the following code.

<g:if test="${scoreValue}">
     var scoreValue=${scoreValue};
</g:if>

However, when I checked the HTML page, I saw the following output:

 var scoreValue={&quot;0&quot;:&quot;Failure&quot;,&quot;1&quot;:&quot;Poor&quot;}

Any assistance on this matter would be greatly appreciated. Thank you!

Answer №1

When it comes to GSP encoding, there are multiple ways to handle it. Along with D. Kossatz's solution, you can explore these alternatives (for more information visit mrhaki's informative Grails Goodness blog)

 var scoreValue=${raw(scoreValue)};

 var scoreValue=${scoreValue.encodeAsRaw()}

It's important to note the potential risk of cross-site scripting vulnerabilities if user input is displayed on the page without protection. As long as you have absolute confidence that only authorized individuals can modify the value and implement appropriate safety measures to verify its validity, you should be in good shape.

Answer №2

Consider using this:

let encodedValue = <g:useCodec encodeAs="none">${scoreValue}</g:useCodec>;

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

Is it possible to utilize a JavaScript framework within a Chrome extension?

Currently, I am developing a chrome extension that adds a toolbar to the DOM dynamically. In order to find, attach, and manipulate elements, I have been using CSS selectors in JavaScript. However, this approach has proven to be fragile as any changes made ...

Utilize JavaScript to append a CSS class to a dynamic unordered list item anchor element

I am working with a list of ul li in a div where I need to dynamically add CSS classes based on the click event of an anchor tag. Below is the HTML structure of the ul li elements: <div class="tabs1"> <ul> <li class="active"> ...

Bootstrap modal with autocomplete feature

How can I display the last entered data by the user in a bootstrap modal? I attempted to use the HTML autocomplete="on" attribute but it did not work, similar to what is shown in this fiddle. After the user submits, on the subsequent attempt, it should pr ...

What is the solution for handling nested promises in Node.js?

I am currently using the node-fetch module for making API calls. I have a function that handles all the API requests and returns both the status code and the response body. The issue I'm facing is that when returning an object with the response data, ...

How to update a value within a deeply nested array in MongoDB and then sort the data

In my document, I have a list of timestamps that are sorted by time: { _id: '1', timestamps: [ { id: '589b32cf-28b3-4a25-8fd1-5e4f86682199', time: '2022-04-13T19:00:00.122Z' }, { id: '781 ...

Saving data submitted through a form using React Hooks and JSON encounters problems with proper storage

I am facing an issue with a form that is supposed to create items labeled as "post" with unique IDs, titles, authors, and content. The desired structure is as follows: { "posts": [ { "id": 1, "title": "F ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form? isEmailExist(): AsyncValidatorFn { return (control: AbstractControl): Observable<any> => { ...

What is the recommended library for managing a task queue in this project?

Is there a library or package available for Node.js that can help me create a task queue with a fixed timeout between the start of each task and an overall callback that is triggered after all tasks have finished? https://i.stack.imgur.com/j1wCY.jpg ...

Is the detailedDescription missing from the JSON-LD schema crawl?

I am currently utilizing the Google Knowledge Graph Search (kgsearch) API to retrieve Schemas from schema.org. However, I am encountering an issue where some nested elements are not being recognized as JSON or I may be overlooking something... url = "http ...

Learn how to serialize JSON data from an API in Flutter

Trying to implement a model in my Flutter app to enhance the functionality. As I am new to Object-Oriented Programming (OOP), I am eager to learn more. Currently, I am facing an issue with decoding API responses from OpenWeather API. The manual decoding me ...

Troubleshooting imagejpeg() Function Failure in PHP Server

I've been working on implementing image cropping functionality for my website. I've managed to send an array of cropped image dimensions (x, y, width, height) to my PHP script. On my localhost, the script successfully crops the image, but unfort ...

Guide to Changing the Value of a Textbox Using Form jQuery

For instance: <form id="example1"> <input type="text" name="example_input"> </form> <form id="example2"> <input type="text" name="example_input"> </form> In the code above, both text boxes have the same name. H ...

Definition of Angular 2 File

I have developed a custom Gantt chart library using D3 in vanilla JavaScript. Now, I am trying to integrate it into my Angular 2 application. After installing D3 via npm and adding the necessary type files and the Gantt chart module to node_modules, I enco ...

Is there a way to conceal a component using Twitter Bootstrap while having the ability to reveal it with the help of

Suppose I generate an HTML element in the following manner, <div id="unique-div" class="concealed">Hello, TB3</div> <div id="unique-div" class="hide-me">Greetings, TB4</div> <div id="u ...

Array<item> JSON

I have these two classes in the backend: Product public class Product implements Serializable { @Transient @JsonSerialize @JsonDeserialize private Set<Branch> branches = new HashSet<>(); //more fields //getters and setters ...

The error TS2339 is indicating that there is no property called myProperty on the type SetStateAction<User>

I'm encountering a TypeScript error while working with React that's leaving me puzzled: <html>TS2339: Property 'subEnd' does not exist on type 'SetStateAction&lt;User&gt;'.<br/>Property 'subEnd' d ...

``There seems to be an issue with the redirect header function in the PHP

Setting up my test site on a local host, I included an ajax request in one of my java-script files to a php script. if(hIF == "true"){ $.ajax({ type: "POST", url: "log_in/login.php", data: {name: userName, pwd: password}, ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

Customize Cell Styling with Bootstrap Full Calendar CSS

I am attempting to implement a Bootstrap calendar feature where cells are colored green if the timestamp is greater than today's date. This can be achieved by: $checkTime > $today cell.css = green background I came across this code snippet on St ...