之前写了一篇
最近把他拿出来更新了下,把demo也搞的更详细了一点
- 加入了blqw.Json,所以支持更多类型参数和返回值
- 优化了对exception的处理
- 增加了分页Pager对象
- 优化了注册页面变量的方式,更安全了
特点
首先他不需要任何的配置文件
没有额外dll ,他是开源的,只要你愿意, 他只有2个cs文件
使用之后前台js调用后台方法都是采用同步模式,这样更加接近C#后台的编程方式
var user = PostAjax8();
var message = ["姓名:"+ user.Name, "年龄:"+ user.Age, "生日:"+ user.Birthday].join("\n\r");
alert(message);
如果想实现异步效果需要使用setTimeout方法,比如这样
text1.value = "正在获取数据...";
setTimeout(function () {
var a = PostAjax1();
text1.value = "服务器返回:" + a;
}, 0);
C#的异常可以反映到js中
所以你可以在js直接使用中的try..catch..来处理它
function ajax8() {
try {
var user = PostAjax8();
var message = ["姓名:" + user.Name, "年龄:" + user.Age, "生日:" + user.Birthday].join("\n\r");
alert(message);
} catch (e) {
alert("出现异常:" + e.message);
}
}
异常堆栈可以通过blqw.Ajax2.ThrowStack=true;设置,将详细堆栈信息也输出到前端页面js中
运行方式
首先是在Page_Load,或者前台页面中<% ... ... %>中加入
Ajax2.Register(this);
在该方法中,判断当前页面参数,如果普通请求,就注册js代码到页面中
debug模式中注册完整js
#region javascript full
#if DEBUG
const string JAVASCRIPT = @"
window.blqw = window.blqw || {};
blqw.Ajax = blqw.Ajax || {};
blqw.Ajax.GetRequest = function () {
if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
return new ActiveXObject('Microsoft.XMLHTTP');
}
}
else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
} blqw.Ajax.Throw = function(e){{
function AjaxError(message,stack,type){{
this.name = 'AjaxError';
this.type = type;
this.message = message;
this.stack = stack;
this.innerError = null;
this.toString = function () {{
return 'message:' + this.message + '\r\n' + 'stack:' + e.stack;
}};
}};
var err = new AjaxError(e.message,e.stack,e.type);
var e1 = err;
while(e.innerError){{
e = e.innerError;
e1.innerError = new AjaxError(e.message,e.stack,e.type);
e1 = e1.innerError;
}}
return err;
}} blqw.Ajax.Exec = function (method, args) {
var getStr = function (obj) {
if (obj == null) return '';
var type = typeof (obj);
switch (type) {
case 'number':
case 'boolean':
return obj.toString();
case 'string':
return encodeURIComponent(obj.replace('\0', '\0\0'));
case 'undefined':
return '';
case 'function':
try {
return arguments.callee(obj());
} catch (e) {
return '';
}
case 'object':
type = Object.prototype.toString.apply(obj);
switch (type) {
case '[object Date]':
return encodeURIComponent(obj.getFullYear() + '-' +
(obj.getMonth() + 1) + '-' +
obj.getDate() + ' ' +
obj.getHours() + ':' +
obj.getMinutes() + ':' +
obj.getSeconds() + '.' +
obj.getMilliseconds());
case '[object RegExp]':
return arguments.callee(obj.toString());
case '[object Array]':
var arr = [];
for (var i in obj) {
arr.push(arguments.callee(obj[i]));
}
return '[' + arr.join(',') + ']';
case '[object Object]':
var arr = [];
for (var i in obj) {
arr.push(i + ':""' + arguments.callee(obj[i]).replace('%22','%5C%22') + '""');
}
if (arr.length === 0) {
return '{}';
}
return '{' + arr.join(',') + '}';
}
break;
}
}
var ajaxdata = '';
if (args.length > 0) {
var arr = [];
for (var i = 0; i < args.length; i++) {
arr.push(getStr(args[i]));
}
ajaxdata = 'blqw.ajaxdata=' + arr.join('\0');
}
url = window.location.href;
var req = blqw.Ajax.GetRequest();
req.open('POST', url, false);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
var ret = req.send(ajaxdata + '&blqw.ajaxmethod=' + method);
if (req.status == 200) {
var html = req.responseText;
var data = eval('(' + html+ ')');
if ('v' in data) {
eval(data.v);
}
if ('e' in data) {
throw blqw.Ajax.Throw(data.e);
} else {
return data.d;
}
} else {
alert('出现错误');
}
}
"; private static void Encode()
{
//var aaaa = new Yahoo.Yui.Compressor.JavaScriptCompressor(JAVASCRIPT, false, Encoding.UTF8, System.Globalization.CultureInfo.CurrentCulture).Compress().Replace("\"", "\"\"");
} #endif
#endregion
完整Js
release模式中注册精简js
#region javascript min
#if !DEBUG
const string JAVASCRIPT = @"window.blqw=window.blqw||{};blqw.Ajax=blqw.Ajax||{};blqw.Ajax.GetRequest=function(){if(window.ActiveXObject)try{return new ActiveXObject(""Msxml2.XMLHTTP"")}catch(c){return new ActiveXObject(""Microsoft.XMLHTTP"")}else if(window.XMLHttpRequest)return new XMLHttpRequest};blqw.Ajax.Throw=function(c){for(var e=function(a,b,c){this.name=""AjaxError"";this.type=c;this.message=a;this.stack=b;this.innerError=null;this.toString=function(){return'message:'+this.message+'\r\n'+'stack:'+e.stack}},a=new e(c.message,c.stack,c.type),d=a;c.innerError;)c=c.innerError,d.innerError=new e(c.message,c.stack,c.type),d=d.innerError;return a};blqw.Ajax.Exec=function(c,e){var a=function(b){if(null==b)return"""";var a;switch(typeof b){case ""number"":case ""boolean"":return b.toString();case ""string"":return encodeURIComponent(b.replace(""\0"",""\0\0""));case ""undefined"":return"""";case ""function"":try{return arguments.callee(b())}catch(c){return""""}case ""object"":switch(a=Object.prototype.toString.apply(b),a){case ""[object Date]"":return encodeURIComponent(b.getFullYear()+""-""+(b.getMonth()+1)+""-""+b.getDate()+"" ""+b.getHours()+"":""+b.getMinutes()+"":""+b.getSeconds()+"".""+b.getMilliseconds());case ""[object RegExp]"":return arguments.callee(b.toString());case ""[object Array]"":a=[];for(var d in b)a.push(arguments.callee(b[d]));return""[""+a.join("","")+""]"";case ""[object Object]"":a=[];for(d in b)a.push(d+':""'+arguments.callee(b[d]).replace(""%22"",""%5C%22"")+'""');return 0===a.length?""{}"":""{""+a.join("","")+""}""}}},d="""";if(0<e.length){for(var d=[],f=0;f<e.length;f++)d.push(a(e[f]));d=""blqw.ajaxdata=""+d.join(""\x00"")}url=window.location.href;a=blqw.Ajax.GetRequest();a.open(""POST"",url,!1);a.setRequestHeader(""Content-Type"",""application/x-www-form-urlencoded; charset=utf-8"");a.send(d+""&blqw.ajaxmethod=""+c);if(200==a.status){a=eval(""(""+a.responseText+"")"");""v""in a&&eval(a.v);if(""e""in a)throw blqw.Ajax.Throw(a.e);return a.d}alert(""出现错误"")};";
#endif
#endregion
精简js
接下来,会反射被标识为AjaxMethod的方法,再加入到页面的js中,比如这样
function PostAjax1(){return blqw.Ajax.Exec('PostAjax1',arguments);}
然后就可以在js中上直接使用 PostAjax1()调用后台的方法了
执行blqw.Ajax.Exec()方法会使用ajax方式请求当前页面,添加post参数,比如
blqw.ajaxdata:{Name:"冰麟轻武",Age:"28",Birthday:"1986-10-29"}
blqw.ajaxmethod:PostAjax7
这时候又会进入blqw.Ajax2.Register方法,会判断blqw.ajaxmethod 如果存在这个参数就会使用Literacy组件反射对应的方法,并使用json组件反序列化参数,
调用后台方法之后再序列化参数并输出到页面中
如果调用后台方法中出现异常,将会序列化异常对象(Exception)到前台,并在js中throw出来