Here is a full JavaScript program that demonstrates how to use the AJAX technique to retrieve data from a server without a page refresh:
This program creates a simple web page with a button labeled "Get Data" and an empty div
element to display the data retrieved from the server.
The program uses the XMLHttpRequest
object to create an HTTP request, it open a GET request to a server-side file called "example.json". The responseType
property is set to "json" so that the response can be parsed as a JSON object.
When the "Get Data" button is clicked, the XMLHttpRequest
's send()
method is called to send the request to the server. The onreadystatechange
event is used to check the status of the request, if the request is successful, the response is parsed as a JSON object and the data is displayed in the output div
element.
This script can be implemented in any software that supports HTML and JavaScript, such as a text editor like Sublime or Atom, and a web browser like Chrome, Firefox or Safari.
Please note that the example.json file should be in the same folder as the HTML file and it should contain a json array of objects with a name property, also note that this code is a simple example, in real scenarios you should handle errors and use a framework like jQuery, Axios or Fetch to simplify the use of AJAX.
No comments:
Post a Comment