• 2009-03-09

    prototype实现ajax请求 - [ajax]

    版权声明:转载时请以超链接形式标明文章原始出处和作者信息及本声明
    http://allantaylor.blogbus.com/logs/36333489.html

    才知道ajax应用并不需要一次又一次createXmlHttpRequest,使用框架,一切变得很轻松
    Prototype仅仅是一个编写好的js脚本库,跟javascript一样,此脚本库只需在页面引用即可
    下载地址: http://prototype.conio.net/dist/prototype-1.4.0.tar.gz
    这是一个完全版本,只需要将文件解压,然后在dest目录下拷贝出prototype.js就可以使用,这个文件不需要任何其他文件,只需要在您的项目中拷贝它,引用它,使用它.
    这里我使用两个脚本文件来对其进行讲解
      <script src="js/prototype.js"></script>
      <script src="js/test.js" ></script>
    在调试的时候使用<script src="js/prototype.js"/>会造成IE页面没有任何显示,也不报错,很不解,希望知道为什么的朋友可以告诉我

    要被赋值的文本框
    <input type="text" id="userName"></input>
    触发事件的button
    <input type="button" value="button" onClick="testGEBI('userName')"/><br>
    用于输出的局部刷新位置
    ss:<span id="ss"></span><br>

    test.js中的函数
    function testGEBI(str){
        //使用$()代替getElementById()
        $(str).value="button";
        //使用$F取文本框值
        ss.innerHTML=$F("userName");
    }
    这里$(element)相当于document.getElementById()
        $F(element)相当于document.getElementById().value
    使用prototype的好处就在于可以简化我们的代码,减少代码量
    其中参数element可以是object对象也可以是id值
    类似的方法还有一些,大家可以去查查

    Prototype还有一些自定义的对象和类
    这里用一个Element对象的empty(element)方法来举例
    页面上布置一个触发事件的按钮
    <input type="button" value="testEmpty" onClick="isEmpty()"/>
    <span id=”ise”></span>
    脚本中加入
    function isEmpty(){
        if(Element.empty("ss")){
            ise.innerHTML="空元素";
        }
    }
    这个方法判断id为”ss”的标签内部是否有元素,如果没有返回true,这个对象还有一些hide(element),show(element)等控制元素显示和隐藏的函数

    以下是ajax相关的内容,prototype同样为ajax提供了相关函数,避免不停的重复编写createXHR()函数,类有很多,这里只介绍一下Ajax.Request类

    脚本中加入
    function getXML(){
        //局部请求的地址
        var url="priceAction";
        //创建的 对象名(这个对象名其实在这里并没有被使用过,当对象一被创建,局部请求就已经发出,所以这里不需要使用这个对象名,它完全可以是匿名的)
        var myAjax = new Ajax.Request(
        url,
        {
            method:'post', //请求方法
            onComplete:showResponse, //回调函数
            asynchronous:true //是否异步
        }
        );
    }
    //回调函数,注意这个回调函数是有参数,用于接收返回的信息
    function showResponse(xmlrequest){
        gx.innerHTML=xmlrequest.responseText;
    }
    页面中加入
    xml:<span id="gx"></span><input type="button" value="getXml" onclick="getXML()"/>

    可以看到请求被正确发出了,没有浏览器的判断,没有手写的open函数,很简洁

    同一页面可以很方便的使用多个XmlHttpRequest对象来进行异步请求
    脚本中再加入
    function getXML2(){
        var url="priceAction";
        var myAjax = new Ajax.Request(
        url,
        {
            method:'post',
            onComplete:showResponse2,
            asynchronous:true
        }
        );
    }

    function showResponse2(xmlrequest2){
        gx2.innerHTML=xmlrequest2.responseText;
    }
    页面中
    xml2:<span id="gx2"></span><input type="button" value="getXml2" onclick="getXML2()"/>

    然后我们编写一个生成随机数的servlet,注意他的地址和上面的url参数一致
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Random;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;


    public class PriceAction extends HttpServlet {

        /**
         * Constructor of the object.
         */
        public PriceAction() {
            super();
        }

        /**
         * Destruction of the servlet. <br>
         */
        public void destroy() {
            super.destroy(); // Just puts "destroy" string in log
            // Put your code here
        }

        /**
         * The doGet method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to get.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out
                    .println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");

            
            Random rand = new Random(System.currentTimeMillis());
            out.write(rand.nextInt(10)+"$"+rand.nextInt(10)+"$"+rand.nextInt(10));
            //System.out.println(rand.nextInt(10)+"$"+rand.nextInt(10)+"$"+rand.nextInt(10));
            out.flush();
            out.close();
        }

        /**
         * The doPost method of the servlet. <br>
         *
         * This method is called when a form has its tag value method equals to post.
         * 
         * @param request the request send by the client to the server
         * @param response the response send by the server to the client
         * @throws ServletException if an error occurred
         * @throws IOException if an error occurred
         */
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            doGet(request,response);
        }

        /**
         * Initialization of the servlet. <br>
         *
         * @throws ServletException if an error occure
         */
        public void init() throws ServletException {
            // Put your code here
        }
    }
    点击两个getXml按钮,可以发现它们并不互相影响,页面也没有被刷新,请求被局部发出,局部刷新.Ajax的框架还有很多,prototype是一个轻量级的


    收藏到:Del.icio.us