分享

mootools-1.2 学习笔记之ajax基本操作

 寂寞如故 2014-09-03
   
     下面的代码分别演示了这三种方式:

复制代码
<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();
});
复制代码

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多