By: Ram Baskar in Ajax Tutorials on 2022年11月28日 [フレーム]
Here is a simple AJAX example with a HTTP GET request:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script>
function makeRequest() {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
document.getElementById('response').innerHTML = httpRequest.responseText;
} else {
alert('There was a problem with the request.');
}
}
};
httpRequest.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
httpRequest.send();
}
</script>
</head>
<body>
<h1>AJAX Example</h1>
<button onclick="makeRequest()">Make Request</button>
<div id="response"></div>
</body>
</html>
In this example, we have a button on the web page that when clicked, it calls the makeRequest() function. This function creates a new XMLHttpRequest object and sets a callback function to handle the server response. It then opens a GET request to the specified URL and sends the request. Once the server responds, the callback function is called to handle the response. In this example, we simply display the response in a div on the web page. If there is a problem with the request or the server responds with a non-200 status code, we display an error message in an alert box.
Note that in this example, we are making a request to a JSON API endpoint and displaying the response on the web page. However, this example can be adapted to work with any type of HTTP request and response.
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
Most Viewed Articles (in Ajax )
A complete sample program in AJAX
How to Make an HTTP Request in AJAX
Latest Articles (in Ajax)
© 2023 Java-samples.com
Tutorial Archive: Data Science React Native Android AJAX ASP.net C C++ C# Cocoa Cloud Computing EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Trends WebServices XML Office 365 Hibernate
Latest Tutorials on: Data Science React Native Android AJAX ASP.net C Cocoa C++ C# EJB Errors Java Certification Interview iPhone Javascript JSF JSP Java Beans J2ME JDBC Linux Mac OS X MySQL Perl PHP Python Ruby SAP VB.net EJB Struts Cloud Computing WebServices XML Office 365 Hibernate