Go through the sample code.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function GetasyData() {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "GetData.aspx", true);
xmlhttp.send();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="GetasyData()">Change Content</button>
</form>
</body>
</html>
Create a new page called GetData.aspx and add the below code in page load event.
GetData.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
//required to keep the page from being cached on the client's browser
Response.ContentType = "text/plain";
Response.Write(DateTime.Now.ToString());
Response.End();
}
The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.
All modern browsers like IE7+, Firefox, Chrome, Opera and Safari has built-in XMLHttpRequest object.
xmlhttp = new XMLHttpRequest();
will create the new XMLHttpRequest object. Old browsers uses ActiveX object.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.readyState == 4
xmlhttp.status == 200
HTTP state is OK.
xmlhttp.open("GET", "GetData.aspx", true);
xmlhttp.send();
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server)
Sending a large amount of data to the server (POST has no size limitations)
Sending user input (which can contain unknown characters), POST is more robust and secure than GET
Response.Expires = -1;
Will keep the page from being cached in the browser.
The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:
Response.ContentType = "text/plain";
No comments:
Write comments