Ajax学习系列2- 核心对象XMLHttpRequest

XMLHttpRequest的杀手锏

         XMLHttpRequest 对象用于在后台与服务器交换数据,可以不需要重新加载页面而达到更新网页局部的目的,根据Ajax的定义(是一种在无需重新加载整个网页的情况下,能够更新局部网页的技术)可知,该对象是Ajax的核心。


用户名校验,两种方式实现

  传统方式:

    

    当点击“检验”按钮时,跳转到另一个页面

   

  (代码见Classic.htmlClassicServer.java后台代码不是重点能看懂就行)

   Classic.html

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        校验用户名是否存在的例子<br/>
        <form action="ClassicServer" method="GET">
            用户名:<input type="text" name="name"/>
            <input type="submit" value="检验"/>
        </form>
    </body>
</html>

   ClassServer.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author TCH
 */
public class ClassicServer extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
          try{
            response.setContentType("text/html;charset=UTF-8");
            PrintWriter out = response.getWriter();
            String old = request.getParameter("name");
            if(old == null || old.length() == 0){
                out.println("用户名不能为空");
            } else{
                String name = new String(old.getBytes("ISO8859-1"));
                if(name.equals("wangxingkui")){
                    out.println("用户名[" + name + "]已经存在,请使用其他用户名");
                } else{
                    out.println("用户名[" + name + "]尚未存在,可以使用该用户名注册");
                }
            }
            out.println("<br/><a href=\"classic.html\">返回校验页面</a>");
        } catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

   

  ajax方式:

    

    校验过程中,始终在一个页面,只是页面的反馈内容更新了。

    (代码见Ajax.htmlAjaxServer.java后台代码不是重点能看懂就行)


    Ajax.html

    

<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <input type="text" id="name"/>
        <input type="button" name="submit" οnclick="submit()" value="AJAX校验"/>
        <div id="message"></div>
			
        <script type="text/javascript">
            var xmlhttp;
            function submit(){
                // 1.创建XMLHttpRequest对象
                if(window.XMLHttpRequest){
                    // IE7,IE8,FireFox,Mozillar,Safari,Opera
                    xmlhttp = new XMLHttpRequest();
                    // 由于Mozillar版本的,由于XML以MimeType开头时,服务端可能会无法工作
                    if(xmlhttp.overrideMimeType){
                        xmlhttp.overrideMimeType("text/xml");
                    }
                }else if(window.ActiveXObject){
                    // IE5,IE6
                    var activexName = ['MSXML2.XMLHTTP.6.0','MSXML2.XMLHTTP.5.0',
                        'MSXML2.XMLHTTP.4.0','msxml2.xmlhttp.3.0','MSXML2.XMLHTTP.2.0',
                        'MSXML2.XMLHTTP.1.0']
                    for(var n=0;n< activexName.length; n++) // 循环尝试
                    {
                        try{
                            xmlhttp = new ActiveXObject(activexName[n]);
                            break;
                        }catch(e){}
                               
                    }
                }else{
                    alert("不能建立XMLHttpRequest对象");
                    return false;
                }

                // 2.注册回调方法
                xmlhttp.onreadystatechange = callback; // 需要方法名
                
                var name=document.getElementById("name").value;
                if(name==null || name==""){
                    alert("用户名不能为空!");
                }
                
                /* 使用GET方式
                // 3.设置和服务端交互的相应参数
                xmlhttp.open("GET","AjaxServer?name="+name,true);// true 采用异步
                
                // 4.设置向服务端发送的数据,启动和服务端的交互
                xmlhttp.send(null); // 主要用在post方式
                 */
               
                // **********使用POST方式
                // 3.设置和服务端交互的相应参数
                xmlhttp.open("POST","AjaxServer",true);
                // POST方式交互所需要增加的代码:设置头信息
                xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
                
                // 4.设置向服务端发送的数据,启动和服务端的交互
                xmlhttp.send("name=" + name); 
                
            }
              
            function callback(){
                // 5.判断和服务端的交互是否完成,判断服务端是否正确返回数据
                if(xmlhttp.readyState ==4){
                    // 表示交互已完成
                    if(xmlhttp.status ==200){
                        // 表示服务器的相应代码是200,正确返回数据
                        // 纯文本数据的接受方法
                        var messageNode = document.getElementById("message");
                        messageNode.innerHTML = xmlhttp.responseText;
                        
                        // xml数据对应的dom对象接受方法
                        // 使用的前提是,服务端需要设置content-type为text/xml
                        // var domXml = xmlhttp.responseXML;
                    }
                }
            }
        </script>
    </body>
</html>





    AjaxServer.java

    

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author TCH
 */
public class AjaxServer extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String old = request.getParameter("name");
            if (old == null || old.length() == 0) {
                out.println("用户名不能为空");
            } else {
                String name = new String(old.getBytes("ISO8859-1"), "gb2312");
                if (name.equals("wangxingkui")) {
                    //4。和传统应用不同之处。这一步需要将用户感兴趣的数据返回给页面段,而不是将一个新的页面发送给用户
                    //写法没有变化,本质发生了改变
                    out.println("用户名[" + name + "]已经存在,请使用其他用户名");
                } else {
                    out.println("用户名[" + name + "]尚未存在,可以使用该用户名注册");
                }

            }
        } finally {
            out.close();
        }
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}

两种方式比较

通过页面变化和代码可以发现:



即使传统方式始终在一个页面进行操作,和页面跳转的实质是一样的,都是刷新整个页面


 从上篇博客Ajax菜鸟学习系列1老技术新思想中的 ajax思想原理图可以容易的看出。


小结

       

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值