In this post I give the demo of jquery ajax to call server side
method and use ajax start event to handling ajax start and display loading image and on ajax stop I
hide loading image after request return response. I use web method to call
server side method and add thread to delay response.
AjaxDemo.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AjaxDemo.aspx.cs" Inherits="AjaxDemo"%>
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml">
<head
runat="server">
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function displayMessage() {
$('#result').html('');
$.ajax(
{
type: "POST",
contentType: "application/json;
charset=utf-8",
url: "AjaxDemo.aspx/GetMessage",
data: "{}",
success: function (result) {
$('#result').html(result.d);
}
})
}
$(document).ajaxStart(function
() {
$("#loading").show();
});
$(document).ajaxStop(function
() {
$("#loading").hide();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align: center; margin-top: 150px;">
<input type="button" value="click me" onclick="displayMessage();" />
<div id="result"></div>
<div id="loading" style="display: none">
<img src="ajax-loader.gif" />
</div>
</div>
</form>
</body>
</html>
AjaxDemo.cs
using System;
using System.Web.Services;
public partial class AjaxDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetMessage()
{
System.Threading.Thread.Sleep(3000);
return "Hello Ajax";
}
}
No comments:
Post a Comment