<!DOCTYPE html>
<html>
<head>
<title>JSON 데이터 로드 예제</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>JSON 데이터 로드 예제</h1>
<button id="loadJsonBtn">JSON 데이터 로드</button>
<div id="jsonDataContainer"></div>
<script>
$(document).ready(function () {
$("#loadJsonBtn").click(function () {
// JSON 데이터를 가져옵니다.
$.getJSON("data.json", function (data) {
// JSON 데이터를 처리하고 화면에 출력합니다.
var jsonDataContainer = $("#jsonDataContainer");
jsonDataContainer.empty(); // 기존 내용을 지웁니다.
$.each(data, function (index, item) {
jsonDataContainer.append("<p>Name: " + item.name + "</p>");
jsonDataContainer.append("<p>Age: " + item.age + "</p>");
jsonDataContainer.append("<hr>");
});
})
.fail(function (jqxhr, textStatus, error) {
// 오류가 발생하면 처리합니다.
console.error("JSON 데이터 로드 실패: " + textStatus + ", " + error);
});
});
});
</script>
</body>
</html>
JSON
[
{
"name": "John Doe",
"age": 30
},
{
"name": "Jane Smith",
"age": 25
},
{
"name": "Bob Johnson",
"age": 35
}
]
1. **HTML Structure**: The document contains a simple HTML structure, including a button (`id="loadJsonBtn"`) that users can click to load JSON data, and a `div` (`id="jsonDataContainer"`) where the loaded data will be displayed.
2. **jQuery Inclusion**: The jQuery library is included via a CDN (Content Delivery Network) link to enable the use of jQuery methods within the document.
3. **JavaScript & jQuery Script**:
- **Document Ready**: The script waits for the document to be fully loaded before executing.
- **Event Handler for Button**: When the "JSON 데이터 로드" (Load JSON Data) button is clicked, an anonymous function is triggered.
- **Loading JSON Data**: The `$.getJSON` method is used to asynchronously fetch JSON data from a file named `data.json`. This method is a shorthand Ajax function, which is equivalent to:
```javascript
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
```
- **Handling Fetched Data**: Upon successful fetching of the JSON data, a callback function is executed, which iterates over the data using `$.each`. For each item in the data, it appends a paragraph (`<p>`) to the `#jsonDataContainer` div, displaying the `name` and `age` from the JSON data.
- **Clearing Previous Data**: Before appending new data, the script clears any existing content in `#jsonDataContainer` using the `empty()` method.
- **Error Handling**: The `.fail()` method is chained to handle any errors that may occur during the fetching process, logging an error message to the console.
### Key Points:
- This example is a straightforward demonstration of using jQuery to interact with JSON data and dynamically update the HTML content based on that data.
- The script is designed to be responsive to user actions (button click) and handles both success and failure scenarios during the data loading process.
- It highlights the use of jQuery for DOM manipulation (emptying and appending elements) and event handling.
- The document is primarily for educational purposes, showing how to asynchronously load and parse JSON data on the client side.
### Possible Improvements:
- For a real-world application, consider adding loading indicators or messages to improve user experience during the data loading process.
- Ensure the JSON data's origin is secure and reliable to avoid cross-origin issues or security vulnerabilities.
- Expand the error handling to provide more specific feedback to the user, potentially explaining why the data failed to load.