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

Creating a Dropdown list using Javascript

I am currently working on implementing inline CRUD operations in MVC 5. When a user clicks a specific button to add new records, it should create a dynamic table row. Below is the JavaScript code I am using: function tblnewrow() { var newrow = ' ...

What is the best way to read a JSON array in Swift without a specific key?

Within my Swift Playground, I have implemented the following code: import Foundation struct PlayerInfo: Decodable{ var PlayerID: String = "" var FirstName: String = "" var LastName: String = "" } var teamRequest ...

Transforming a curl command into an AJAX request

Can someone help me with using an API by inputting a curl command through AJAX? Any guidance is greatly appreciated. Here is the curl command I am struggling with: curl -H “Authorization: Token #{auth_token}” -X GET http://localhost:3000/api/v1/basket ...

Switching Over to Burger Menu

I created a burger menu using HTML, CSS, and jQuery that switches from a full-width menu to a burger menu. However, I'm facing an issue with toggling the dropdown when the menu collapses. Here's my code: <!DOCTYPE html> <html> < ...

Improving the Sum of Pairs solution on Codewars

Seeking assistance in optimizing a solution for a problem that has already been identified. However, the existing code is not efficient when dealing with large arrays - view the problem on codeWars : Sum of Pairs Below is the current code snippet: var s ...

Parallel ajax function

After creating a form for registering new accounts, I wanted to ensure that the chosen email is available by checking it against a webservice. However, this process takes a few seconds. Let's take a look at the method used: function validateEmail(ema ...

Transform the jQuery Mobile slider into a jQuery UI slider and update the text

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script> function modifycontent() { if (document.getElementById("slider").value<33) { $("#1").fadeIn("slow"); $("#2").fadeOut("slow"); ...

Is there a way to retrieve data from my JSON file located in the public folder within Next.js 13.3?

My current challenge involves retrieving JSON data from the public folder. async function fetchData() { try { const response = await fetch('/data.json'); const jsonData = await response.json(); return jsonData; } catch (error) { ...

Seeking guidance on navigating back to AJAX results using the back button

I am currently working on resolving the navigation issue involving the back button in my application. Here's the situation: On the homepage, there is a search form that communicates data through $.ajax(). The results are loaded via ajax, and their li ...

The form response values consistently show as undefined, attempting to send them to the backend with no success so far after trying two different approaches

I've tried approaching this issue in two different ways, but both times I end up with a value of "undefined" instead of the user input from the form. Just to give some context, I'm using material UI forms for this project. The first approach inv ...

Is it possible to encounter a MongoDB error for the $or operator in a correctly formatted query?

Here is the problem I am facing: const users = this.mongo.db.collection('Users') let query = { '$or': [ { "email": {'$eq': req.body.email }}, {"username": {'$eq': req.body.username }} ] } users.fi ...

Managing State with Vuex: Storing Getter Results in the State

I'm encountering an issue with my Vuex.Store: My goal is to retrieve an object (getter.getRecipe) by using two state entries as search criteria (state.array & state.selected) through a getter. Then, I want to store the outcome in my state (state. ...

Encountering a 404 error when making a basic WCF request through IIS using jQuery

I'm facing an issue that seems to be a common one - I am trying to connect a WCF service hosted on local-IIS with an ASP.NET WebApp also hosted on local-IIS. The web app can successfully access the .svc file from the AJAX call below, but when I add /G ...

I must interact with the video within the iframe by clicking on it

I am trying to interact with an iframe video on a webpage. Here is the code snippet for the video: <div class="videoWrapper" style="" xpath="1"> <iframe width="854" height="480" src="xxxxxxx" frameborder="0" allow="autoplay; encrypted-media" all ...

Struggling with incorporating a button into a ReactJS table

I am trying to display a (view) button in the table, but I encountered the following error: Module parse failed: Unexpected token < in JSON at position 165 while parsing near '...2021", "view": <button type="submit...' You m ...

How can I add page transitions to my simple HTML website?

Working on an internal website project for my office using vue.js has been a rewarding experience. I appreciate how easily it allows me to manage multiple pages with dynamic content and seamless transitions. Unfortunately, my IT department is hesitating to ...

Show an image in JPEG format using JavaScript within an img tag

Suppose http://example.com/image returns unique image data in response headers and the image itself. Each request to http://example.com/image generates a different image that is not related to the request itself. Besides the image, additional information s ...

Is there a way to prevent a form from automatically submitting once all inputs have been completed? (Using react-hook-form)

After creating a multi-step-form using shadcn, next, zod, and react-hook-form, I encountered an issue where the form is being submitted on step 3 instead of when clicking the submit button. form.tsx const form = useForm<Inputs>({ resolve ...

Adding a Resource Bundle to a Vue project

I am looking to integrate the ResourceBundle package into my Vue project. After installing it with the following command: npm install resource-bundle I discovered these exported functions in the index.js file of the ResourceBundle package: export functi ...

What is the best way to determine if a child div exists within a parent div?

Is there a way to determine if any div exists within the parent div? In my current scenario, I am adding two divs inside the parent div like this. $('#realTimeContents').append("<div style='width:22%; float: left; font-size:18px; line- ...