mootools教程(一):mootools 初探之ajax应用
在使用mootools的ajax应用之前,你应该确保你已下载如下文件:
Moo.js、Function.js、Array.js、String.js、Element.js、Ajax.js
在mootools.net 的download 页面上最下方有三个源代码格式:
使用‘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[”] 接受即可