ajax可通过直接写源码实现,但有点繁琐,现在流行的ajax框架都集成了ajax的功能,而且写起来非常简单方便。当然mootools也不例外。mootools是一个非常优秀的javascript的库,有些地方跟prototype颇有相似(指按面向对象做js)。mootools的Request实现了对XMLHttpRequest的功能包装类,下面是我写的一个小示例:
function scoring(score){ //var url = document.getElementById("url").value; var url = 'test'; var pingRequest = new Request({ method: "post", url: "http://www.nowamagic.net/librarys/veda/", data: score, onSuccess: function(responseText){ if(responseText=="success"){ //alert(responseText); } else{ //alert(responseText); } }, onFailure: function(){ //alert(responseText); } }); pingRequest.send("url="+ url +"&score=" + score + "&id=" + id); }
在后台可以使用$_POST[]来获得ajax传过来的数据。
ajax类的使用:
var ajax = new Ajax(url, options); ajax.request();
url是提交到后台处理的路径。options有2个经常使用的参数:{onComplete:handleFun,data:postArgs}
function handleFun(req){ alert(req); }
onComplete参数指向处理返回的文本函数;data(老版本用postBody名)是按doPost方式提交的字符串。
下面用ajax的2种方法提交form表单(相当于点击form中的submit按钮):
<form action="test.php" id="form1"> <input name="user_name" /> <input name="user_id" /> <input type="button" onclick="ajaxSubmit();" /> </form>
方法1:
function ajaxSubmit(){ var postArgs = $('form1').toQueryString(); new Ajax('test.php', {data:postArgs,onComplete:handleFun}).request(); }
方法2:
function ajaxSubmit(){ var postArgs = $('form1').toQueryString(); $('form1').send({onComplete:showResponse,data:postArgs}); }
$()函数相当于js的document.getElementById(),toQueryString()函数是得到form中提交元素的字符串。
用例1时无需在form中指定action,而必须指定Ajax中的url,例2则必须指定form中action,而无需指定Ajax中的url,另外在 test.php 中接受参数一律用 $_POST[''] 接受即可。
下面再来几个示例:
示例一
<script type="text/javascript"> window.addEvent("domready",function(){ $("send").addEvent("click",function(){ var url="nowamagic.php?areaid="+$("areaidvalue").value+"&say="+escape($("say").value); // escape()是处理编码函数,没有它传替中文时会出乱码 new Ajax(url,{method:'post',onComplete:function(){ $("Content").innerHTML=this.response.text; alert('发表成功!'); }}).request(); }); }); </script>
示例二
<script type="text/javascript"> window.addEvent("domready",function(){ $('btnSent').addEvent('click',function(){ if($('txtContent').innerText==''){ alert('发送内容不能空!'); return; } var url='Default2.aspx'; var postData=$("postMessage").toQueryString(); new Ajax(url,{method:'post',onComplete:function(){ $('messageBox').innerHTML += this.response.text; } }).request(postData); }); }); </script>
示例三
<script type="text/javascript"> window.addEvent("domready",function(){ $('myForm').addEvent('submit', function(e) { new Event(e).stop(); if($("message").value==""){ alert('请输入要发送的消息'); return; } this.send({ onComplete: function() { var request=Json.evaluate(this.response.text); $("messagebox").innerHTML=request.msg; $("namebox").innerHTML=request.name; alert('发送成功!'); } }); }); }); </script>