Present a Java-generated JSON object on a JSP page using JavaScript

Hello, I am currently working on creating a Json object in Java and would like to display the same JSON object in JSP using JavaScript. Essentially, I am looking to add two more options in my select box using Ajax. The Ajax is being called and I can see the output in the response, but I am having trouble adding the values to the dropdown. Any assistance would be greatly appreciated. I am aiming to achieve this using JavaScript only.

{"value1":"label1","value2":"label2"}

Java Code:

Map<String, String> options = new LinkedHashMap<String, String>();
options.put("value1", "label1");
options.put("value2", "label2");

String json = new Gson().toJson(options);
//  json = "DataObject: [" +json+ "]";
System.out.println(json);

response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
response.getWriter().write(json);

Javascript :

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var responseJson=xmlhttp.responseText;
        alert(responseJson);
        var carobj = eval ("(" + responseJson + ")");
        select = document.getElementById("selector");
        for (var i = 0; i < carobj.DataObject.length; i++) {
            var d = carobj.DataObject[i];
            select.appendChild(new Option(d.value1, d.value2));
        }
    }
};

Jsp :

<select id="selector" onchange="showState(this.value)" >
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
</select>

Answer №1

There is no mention of a DataObject in the JSON provided. The JSON appears to be an object rather than an array, so using .length or numeric indexes will not work. To iterate over the properties, use for (key in obj).

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var responseJson = xmlhttp.responseText;
    alert(responseJson);
    var carobj = JSON.parse(responseJson);
    select = document.getElementById("selector");
    for (var value in carobj) {
      select.appendChild(new Option(value, carobj[value]));
    }
  }
};

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

Error 504 occurs on Express.js due to a timeout issue while a timer is active

Encountering a "504 Gateway Timeout" error on my Express.js application when a JavaScript timer is set to run every 20 seconds. Here is the code for my Express.js listener and the timer: const express = require('express') const app = express() ...

Issues arise when the Angular controller fails to load

I'm experiencing an issue with my Angular controller where the code inside its constructor is not running. Here's a snippet of the relevant pieces: conversationcontrollers.js: var exampleApp = angular.module('exampleApp',[]); console ...

I often find myself pondering the significance of objects such as [, thisArg]

At times, I delve into JavaScript code on MDN and come across some confusing syntax like [, thisArg]... for instance, arr.map(callback(currentValue[, index[, array]])[, thisArg]) In this scenario, I am aware that a callback function is required. But what ...

How can you determine if all specified events have been triggered in jQuery?

I am implementing custom triggered events following asynchronous calls, and I'm in need of a method to determine when all the events have been triggered. For instance: var ajaxCall1 = function(){ $.ajax({ url: "someUrl.html", com ...

The issue with the jQuery function lies in its inability to properly retrieve and return values

Within my code, I have a function that looks like this: $.fn.validate.checkValidationName = function(id) { $.post("PHP/submitButtonName.php", {checkValidation: id}, function(data) { if(data.returnValue === true) { name = true; } else { ...

Utilize Node.js driver to export a Mongo collection into a JSON file

How can I export a MongoDB collection to a JSON format using the Node.js driver and fs.writeFile? ...

Using React JS to automatically execute an event based on a specific state value

Is there a way to initiate an action from a main component when the child component's state reaches a specific value? Let's consider a scenario where I have a Parent component and a Child component, with the parent's state containing active ...

The onClick event in React/NextJS is not functioning properly when applied to an external component

One dilemma I am facing involves my main page and a button component that I have created to be reused throughout my project. Strangely, when I add the onClick event to the external component, the click event does not seem to work. However, if I create the ...

A guide on applying bold formatting to a specific section of text in React

I have a collection of phrases structured like so: [ { text: "This is a sentence." boldSubstrings: [ { offset: 5, length: 2 } ] } ] My goal is to display each phrase as a line using the following format: ...

Trigger the UseEffect() function in a Material UI Dialog only when the dialog is open

In my project, I have a parent component that includes a Material UI Dialog as a child component. The purpose of this dialog is to fetch and display data from a REST API. Currently, I am using the UseEffect() function in the Dialog component to achieve th ...

Dygraphs: Utilizing two y-axes in a single series

I'm interested in plotting a single series with two synchronized y-axes that display different units, such as °F and °C temperatures. I want the data to be readable from both axes, but only one set of points should be plotted. Here are some approac ...

The useNavigate() hook from react-router-dom is not properly setting the id in the URL path

I am currently using react-router-dom v6 for my routing needs. My goal is to pass an ID in the navigate URL path. Here is the onClick method and button code that I am working with: let navigate = useNavigate(); const routeChange = (id) => { let ...

Initiating communication with a web service API

I am struggling to retrieve data from a web service API and I can't seem to display anything. As a newcomer to AngularJS, I would greatly appreciate any assistance. Below is the controller and factory code that I am currently using: Controller app.c ...

Having trouble sending a json object to ASP MVC endpoint

I am attempting to send a custom Json object to an ASP.NET MVC controller, but for some reason it is not working correctly. Here is my JavaScript code: var myData = { "Message": "Another message", "Value": 4, "FirstItem": { "ItemName" ...

Ways to expose an object in a Node module

One of my modules relies on a parsing functionality, with other modules needing to query the values provided by this parser. I have some key questions regarding its design: How should I approach building it in terms of design aspects? Which method should ...

What is the best way to write an SQL query to safely insert a record into a table with a dynamic name?

I'm working on a function that can insert a record into a table in PostgreSQL. The catch is that the table name needs to be a parameter for the function, and the column names are determined dynamically. To ensure protection against SQL Injection, I am ...

Verification is required for additional elements within the div block once a single checkbox has been selected

Currently, I am working in PHP using the CodeIgniter framework. I have a question regarding implementing a functionality with checkboxes and validation using jQuery. Here is the scenario I want to achieve: There are four checkboxes, and when one checkbox ...

The current Webpack configuration for production fails to account for importing CSS files

I am struggling to figure out how to properly load a static site that is not located in the root folder: let HWPTest = new HtmlWebpackPlugin({ template: __dirname + "/src/artists/test.html", filename: 'artists/test.html', favicon: &apos ...

The TouchableOpacity function is triggered every time I press on the Textinput

Every time I press on a text input field, the login function is called This is the touchable statement: <TouchableOpacity style={InputFieldStyle.submitButton} onPress={this.login(this.state.email, this.state.password)}> <Text ...

Object with a specific name sitting within an array nested within another object

I have a node.js model that includes an array called keys containing multiple objects. I am looking to display these named objects in the view. Below is the model: var mongoose = require('mongoose'); var website = require('./website' ...