本文執行個體講述了jQuery+Ajax實作限制查詢間隔的方法。分享給大家供大家參考,具體如下:
Jquery異步查詢加載效果
.span_query { cursor:pointer;}
$(function () {
$(".span_query").click(function () {
var val = $(this).attr("data-value");
var id = $(this).attr("id");
AjaxQuery($(this),val);
});
});
function AjaxQuery(obj, v) {
$.ajax({
url: 'Ajax/Handler.ashx?queryType=score&queryValue=' + v,
type: 'POST',
dataType: 'text',
timeout: 10000,
cache: false,
beforeSend: LoadFunction,
error: erryFunction,
success: succFunction
})
function LoadFunction() {
obj.html('
![](/image/Images/loading02.gif)
');
}
function erryFunction() {
obj.html('error');
}
function succFunction(tt) {
obj.html('');
obj.html(tt);
}
}
姓名 | 國文 | 數學 | 英語 |
張三 | 查詢 | 查詢 | 查詢 |
using System;
using System.Web;
using System.Web.SessionState;
//Handler.ashx
public class Handler : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string queryType = context.Request["queryType"];
string queryValue = context.Request["queryValue"];
if (context.Session["preQuery"] == null) //第一次查詢
{
context.Session["preQuery"] = queryValue + "@" + DateTime.Now.AddDays(-1);
context.Session["currQuery"] = queryValue + "@" + DateTime.Now;
}
else //存在上次查詢
{
string[] preStrs = context.Session["currQuery"].ToString().Split('@');
context.Session["preQuery"] = queryValue + "@" + preStrs[1]; //重置為目前查詢參數+上次查詢時間
context.Session["currQuery"] = queryValue + "@" + DateTime.Now;
}
string[] strs=context.Session["preQuery"].ToString().Split('@');
if (strs[0] == queryValue) //同一請求限制查詢間隔
{
DateTime preTime = Convert.ToDateTime(strs[1]);
DateTime nowTime = DateTime.Now;
bool flag = CheckQueryTimeSpan(preTime, nowTime, 3);
if (flag)
{
context.Response.Write("查詢間隔3秒");
}
else
{
context.Response.Write("98");
}
}
context.Response.End();
}
///
/// 判斷本次查詢和上次查詢間隔是否小于指定秒數
///
/// 上次查詢時間
/// 本次查詢時間
/// 指定秒數
///
public bool CheckQueryTimeSpan(DateTime preTime, DateTime nowTime, int timeSpan)
{
TimeSpan ts = nowTime - preTime;
int difference = ts.Seconds;
bool flag = (difference < timeSpan) ? true : false;
return flag;
}
public bool IsReusable {
get {
return false;
}
}
}
希望本文所述對大家jQuery程式設計有所幫助。