下面的代码分别演示了这三种方式: <div id="result">Waiting for the request to happen.</div> <div id="gallery"></div> <input id="loadTxt" type="button" value="loadTxt" /> <input id="loadJson" type="button" value="loadJson" /> <input id="loadHtml" type="button" value="loadHtml" /> <script language="javascript" type="text/javascript"> /*******************************Request**************************************/ $('loadTxt').addEvent('click', function(e) { var req = new Request({url: 'http://localhost:21087/data/data.txt', method:'get' , evalScripts:true, onSuccess: function(responseText) { $('result').set('text', responseText); }, //Our request will most likely succeed, but just in case, we'll add an //onFailure method which will let the user know what happened. onFailure: function() { $('result').set('text', 'The request failed.'); } }).send(); }); /*****************************Request.JSON*********************************/ var images_path = 'http://localhost:21087/images/'; var gallery = $('gallery'); var addImages = function(images) { images.each(function(image) { var el = new Element('div', {'class': 'preview'}); var name = new Element('h3', {'html': image.name}).inject(el); var desc = new Element('span', {'html': image.description}).inject(name, 'after'); var img = new Element('img', {'src': images_path + image.src}).inject(desc, 'after'); var footer = new Element('span').inject(img, 'after'); if (image.views > 50 && image.views < 250) footer.set({'html': 'popular', 'class': 'popular'}); else if (image.views > 250) footer.set({'html': 'SUPERpopular', 'class': 'SUPERpopular'}); else footer.set({'html': 'normal', 'class': 'normal'}); el.inject(gallery); }); }; $('loadJson').addEvent('click', function(e) { e.stop(); var request = new Request.JSON({ url: 'http://localhost:21087/data/data.json', method:'get' , onComplete: function(jsonObj) { addImages(jsonObj.previews); } }).send(); }); /****************************Request.HTML**********************************/ $('loadHtml').addEvent('click', function(e) { var req = new Request.HTML({url:'http://localhost:21087/data/data.htm', method:'get' , onSuccess: function(html) { //Clear the text currently inside the results div. $('result').set('text', ''); //Inject the new DOM elements into the results div. $('result').adopt(html); }, //Our request will most likely succeed, but just in case, we'll add an //onFailure method which will let the user know what happened. onFailure: function() { $('result').set('text', 'The request failed.'); } }).send(); }); </script> </body> </html> 下面是其演示效果:
因为在.net开发下经常使用控件,特别是用户控件,所以我在ajaxhelper基础上做了一些修改,使 mootools支持用户控件的调用,当然使用的机制还是在请求的aspx中使用base.LoadControl方法。 其代码如下:
private void Page_Load(object sender, EventArgs e) { //AjaxTemplate为请求的ascx控制 if (base.Request.Params["AjaxTemplate"] != null) { try { this.AjaxCallBackForm.Controls.Add( base.LoadControl(base.Request.Params["AjaxTemplate"].ToLower().EndsWith(".ascx") ? ascxpath + base.Request.Params["AjaxTemplate"] : (ascxpath + base.Request.Params["AjaxTemplate"] + ".ascx"))); } catch { } } }
而其ajaxhelper的js代码修改如下:
var AjaxProxyUrl = new String("http://localhost:21087/ajax.aspx?"); var AjaxHelper = { Updater : function(ajaxTemplate, output, params, onComplete) { if (typeof output == 'string') { output = $(output); } var FormatContent = function(str) { var content = new String(str); var prefix = new String("<!--AjaxContent-->"); return content.substring(content.indexOf(prefix, 0) + prefix.length, content.indexOf('</form>', 0)); } new Request({url: AjaxProxyUrl + params + '&AjaxTemplate=' + ajaxTemplate, method:'get' , evalScripts:true, onSuccess: function(responseText) { if (output != null) { output.set('text', FormatContent(responseText)); } if (onComplete != null) { onComplete(FormatContent(responseText)) } }, onFailure: function() { output.set('text', 'The request failed.'); } }).send(); } }
另外我还做了一个ajax调用ashx的例子,基本上是proxy方式,使用webclient调用请求的ashx链接,其代码 如下所示:
public class proxy : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { base.Response.ContentType = "text/plain"; string remoteurl = base.Request.QueryString["remoteurl"]; string output = null; if (remoteurl != null) { try { WebClient webclient = new WebClient(); webclient.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
StreamReader streamReader = new StreamReader(webclient.OpenRead(remoteurl), Encoding.UTF8); output = streamReader.ReadToEnd().Trim(); streamReader.Close(); Response.Write(ToJavaScriptString(output)); } catch (Exception ex) { Response.Write(ToJavaScriptString(ex.Message.Trim())); } finally { Response.End(); } } } public static string ToJavaScriptString(string str) { return str.Replace("\n", "").Replace("\r", "").Replace(@"\", @"\\"). Replace("'", @"\'").Replace("\"", "\\\"").Replace("/", @"\/"); }}
其js调用与其它mootools并无什么区别,主要是url中进行了相应的参数绑定(很偷 懒):
$('loadAshx').addEvent('click', function(e) { new Request({url: 'http://localhost:21087/proxy.aspx? remoteurl=http://localhost:21087/usercontrol/AshxSample.ashx?username=daizhj', method:'get' ,evalScripts:true, onSuccess: function(responseText) { $('result').set('text', responseText); }, onFailure: function() { $('result').set('text', 'The request failed.'); } }).send(); }); |
|
来自: 寂寞如故 > 《mootools》