Programming Tutorials

(追記) (追記ここまで)

A complete sample program in AJAX

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.




(追記) (追記ここまで)


Add Comment

JavaScript must be enabled for certain features to work
* Required information
1000

Comments

No comments yet. Be the first!
(追記) (追記ここまで)
(追記) (追記ここまで)

AltStyle によって変換されたページ (->オリジナル) /