欢迎大家来我的Bolg作客!在这里我们将为您提供及时全面的IT信息……

mootools教程(一):mootools 初探之ajax应用

在使用mootools的ajax应用之前,你应该确保你已下载如下文件:
Moo.js、Function.js、Array.js、String.js、Element.js、Ajax.js
在mootools.net 的download 页面上最下方有三个源代码格式:

  • Packer Compression:是压缩过的版本,不适合学习
  • No Documentation:只是去掉解释文档的
  • No Compression:这个是包含解释文档,适合学习阶段使用。

    使用‘ajax’class
    我们先看一下’ajax’这个类的源代码:

    var Ajax = ajax = new Class({
    setOptions: function(options){
    this.options = {
    method: ‘post’,
    postBody: ”,
    async: true,
    onComplete: Class.empty,
    update: null,
    evalScripts: false
    };
    Object.extend(this.options, options || {});
    },
    initialize: function(url, options){
    this.setOptions(options);
    this.url = url;
    this.transport = this.getTransport();
    },

    你可以看到这个类由new Ajax(url,options)进行初始化,url则是你所在服务器的文件路径
    语法:

    new Ajax(url,options).request();

    var ajax = new Ajax(url,options);
    ajax.request();

    下面是一个简单的使用 ajax.js 的例子:
    新建ajax.php

    <body>
    <div id=”content”>Welcome to Fackweb’s Blog</div>
    </body>

    js代码:

    new ajax(’test.php’,{onComplete: showResponse, update: ‘content’}).request();
    function showResponse(request){
    alert(request);
    }

    当然你也可以这样:

    new ajax(’test.html’,{onComplete: function(request){$(’content’).innerHTML=request}}).request();

    这里可以将update: ‘content’ 去掉 因为他和onComplete后的函数 做同一件事情.

    还有就是传递参数:

    new ajax(’test.php’,{
    postBody:’name=fackweb&sex=’man”,
    update:’content’}
    }).request();

    下面是两个传递表单参数的例子:

    新建form:

    <form action=”test.php” id=”form1″>
    <input name=”nickname” />
    <input name=”sex” />
    <input type=”button” onclick=”ajaxRequest()” />
    </form>

    例1:

    function ajaxRequest(){
    var postArgs = $(’form1′).toQueryString();
    //获取表单form1的参数以name=fackweb&sex=man的格式
    new Ajax(’test.php’,{
    postBody:postArgs,
    update:’content’}
    ).request();
    return false;
    }

    例2:

    function ajaxRequest(){
    $(’form1′).send({update:’content’});
    return false;
    }}

    注意这两个例子区别:
    用例1时无需在form中指定action,而必须指定Ajax中的url
    例2则必须指定form中action,而无需指定Ajax中的url
    另外在 test.php 中接受参数一律用 $_POST[”] 接受即可

  • posted @ 2008-10-31 11:00  Cyrus Dai  阅读(743)  评论(0编辑  收藏  举报
    Copyright ? 戴超 2008-10-30---9595-95-95