Handling Server Responses and Updating the Webpage
๐ฅ Handling Ajax Responses
Once an Ajax request is completed, handling the server response correctly is crucial to ensure a smooth user experience. Common response formats include JSON, XML, HTML, and plain text.
๐งช Example: Updating Content with JSON Data
fetch('api/data')
.then(response => response.json())
.then(data => {
document.getElementById('result').innerHTML = `User: ${data.name}, Age: ${data.age}`;
});
๐ Handling Different Data Types
| ๐๏ธ Format | ๐ Usage |
|---------------|----------------------------------------------------------------------|
| ๐งพ JSON | Typical for data exchange; parsed into JavaScript objects |
| ๐งฌ XML | Used in legacy systems; parsed with DOM parsers |
| ๐งฑ HTML | Directly inject into DOM as `innerHTML` |
| ๐ Plain Text | For simple messages or logs |
๐ก๏ธ Proper parsing and validation are essential, especially with JSON and XML, to prevent security issues like XSS or malformed data errors.