嘿世界
的一个星期五的下午,你想要做的一些热点和时髦的代码,使用webMethods和AJAX,但你再遇到的问题和微软的Ajax实现的超额行李。为什么不使用jQuery?以及与此整齐下面的代码片段,你现在可以调用一个ASP.NET页面中的所有ASP.NET AJAX客户端脚本库的行李没有一个WebMethod!所有你需要的是ASP.Net,jQuery和jQuery的JSON库插件提供一点点的JSON魔术
只需将其粘贴到一个JavaScript文件的代码和引用后,您最喜欢的版本的jQuery库,创建一个新的jQuery的方法称为quot; webMethodquot;(function ($) {
$.webMethod = function (options) {
var settings = $.extend({
'methodName': '',
'async': false,
'cache': false,
timeout: 30000,
debug: false,
'parameters': {},
success: function (response) { },
error: function (response) { }
}, options); var parameterjson = "{}";
var result = null;
if (settings.parameters != null) { parameterjson = $.toJSON(settings.parameters); }
$.ajax({
type: "POST",
url: location.pathname + "/" + settings.methodName,
data: parameterjson,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: settings.async,
cache: settings.cache,
timeout: settings.timeout,
success: function (value) {
result = value.d;
settings.success(result);
},
error: function (response) {
settings.error(response);
if (settings.debug) { alert("Error Calling Method \"" + settings.methodName + "\"\n\n+" + response.responseText); }
}
});
return result;
};
})(jQuery);
以下参数:methodName的
表示调用服务器端方法的名称异步确定是否jQuery是等待服务器端进程完成。缓存确定如果jQuery将追加缓存头的请求。超时超时等待服务器响应调试当设置为true,一个JavaScript警告框显示,如果在服务器上发生的任何运行时错误。参数一个对象,包含任何参数传递给服务器端的方法。成功一个回调函数,这是运行时请求成功完成。从服务器端函数的结果作为参数传递。错误一个回调函数运行时要求以某种方式失败。标准错误对象作为参数传递。
下面这个片断来电显示GETDATE()的WebMethod{C}此函数被调用的C#代码隐藏多数民众赞成:
注意:所有重要的[WebMethod]"宣言",它告诉ASP.NET工作其服务器端ASP.NET AJAX魔法......[WebMethod]
public static string GetDate(int client)
{
return string.Format("{0} says {1}", client, DateTime.Now.ToString("r"));
}
单纯!和所有的几行代码 - 一个非常小的足迹。感谢这里的jQuery JSON的插件优秀的JSON转换例程。| JCrocker