Home >Web Front-end >CSS Tutorial >Working with JSON Data in an HTML Environment

Working with JSON Data in an HTML Environment

WBOY
WBOYOriginal
2024-08-20 18:41:15338browse

Working with JSON Data in an HTML Environment

I’ve recently started using JSON in my web development projects and encountered an interesting issue while trying to integrate it with HTML using JavaScript. Specifically, I used the fetch function to retrieve JSON data, which worked great for logging the data in the console. However, I ran into some challenges when trying to display this data in an HTML input field. Instead of showing the actual data, it either displayed "undefined" or "[object Object]". I suspect this is due to asynchronous behavior, and I read that using async/await might solve this. However, this led to an error related to ES version 8, which has been difficult to troubleshoot since most of the resources are geared towards more complex projects. Below is the code I’m currently working with:






JSON Fetch Example







CSS File (json_example.css)

css

#jsonInput {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 400px;
height: 30px;
font-size: 16px;
padding: 5px;
}
JavaScript File (json_example.js)

javascript

`document.addEventListener("DOMContentLoaded", function() {
const jsonUrl = 'http://localhost:8080/data/person.json';

fetch(jsonUrl)
    .then(response => response.json())
    .then(data => {
        console.log(data);
        document.getElementById("jsonInput").value = JSON.stringify(data);
    })
    .catch(error => console.error('Error fetching JSON:', error));

});
JSON File (person.json)

json

{
"firstName": "Jane",
"lastName": "Doe",
"age": 25,
"city": "Los Angeles"
}`

The code fetches JSON data and displays it in the console without any problems. However, when attempting to insert this data into an HTML text input field, it either results in an "undefined" value or displays "[object Object]" rather than the desired JSON content. Using async/await to handle the asynchronous nature of the fetch might help, but it leads to compatibility issues with ES version 8.

How can I properly display the JSON data within an HTML element like a text input field?
What are the best practices for handling asynchronous operations when working with JSON in a basic web project?

The above is the detailed content of Working with JSON Data in an HTML Environment. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn