`
webcode
  • 浏览: 5948250 次
  • 性别: Icon_minigender_1
  • 来自: 上海
文章分类
社区版块
存档分类
最新评论

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" onclick="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思想原理图可以容易的看出。


小结


分享到:
评论

相关推荐

    AJAX核心技术1-XMLHttpRequest对象的使用

    [王兴魁]AJAX核心技术1-XMLHttpRequest对象的使用

    AJAX核心技术2-XMLHttpRequest对象的扩展问题

    [王兴魁]AJAX核心技术2-XMLHttpRequest对象的扩展问题

    Ajax核心对象XMLHTTPRequest

    Ajax核心对象XMLHTTPRequest详细参数及例子

    Ajax之XMLHttpRequest详解

    详解Ajax的核心对象XmlHttpRequest

    Ajax 创建XMLHttpRequest对象,兼容所有主流浏览器(IE5除外)

    经测试,用此方法创建XMLHttpRequest对象,在运用AJAX的时候,可以的兼容IE6,IE7,IE8,Opera,Safari,Google Chrome,fireFox。主流的应该就这些吧?theWorld,遨游等浏览器都是以IE为核心的,所以肯定也没问题。 另外...

    AJAX核心-XMLHTTP对象

    ajax技术中承载数据传输任务的xmlhttprequest介绍及其相关api

    锋利的jQuery书中源代码

    找了很久终于搞到了锋利的jQuery书中源...第3篇介绍了Ajax的核心对象---XMLHttpRequest. 第4篇介绍了jQuery中的$.ajax()方法. 第5篇介绍了jQuery加载并解析xml. 第6篇是第七章的插件的API 第7篇是jQuery API速查表.

    锋利的jquery——1

    第3篇介绍了Ajax的核心对象---XMLHttpRequest. 第4篇介绍了jQuery中的$.ajax()方法. 第5篇介绍了jQuery加载并解析xml. 第6篇是第七章的插件的API 第7篇是jQuery API速查表. 本书循序渐进的对jQuery的各种方法和...

    PHP100视频教程 48:Ajax+PHP快速上手及应用

    2、创建XMLHttpRequest对象对于Ajax,最核心的一个对象是XMLHttpRequest,所有的Ajax操作都离不开对这个对象的操作xmlHttp = new XMLHttpRequest();3、XMLHttpRequest对象相关方法XMLHttpRequest.open(传递方式,地址...

    XMLHttpRequest对象的使用

    王兴魁老师Ajax核心技术XMLHttpRequest源码

    解析ajax核心XMLHTTPRequest对象的创建与浏览器的兼容问题

    MLHttpRequest 对象是AJAX功能的核心,要开发AJAX程序必须从了解XMLHttpRequest 对象开始。 了解XMLHttpRequest 对象就先从创建XMLHttpRequest 对象开始,在不同的浏览器中创建XMLHttpRequest 对象使用不同的方法: ...

    PHP100视频教程 48:Ajax PHP快速上手及应用.rar

    对于Ajax,最核心的一个对象是XMLHttpRequest,所有的Ajax操作都离不开对这个对象的操作 xmlHttp = new XMLHttpRequest(); 3、XMLHttpRequest对象相关方法 XMLHttpRequest.open(传递方式,地址,是否异步请求) ...

    ajax教程 在线视频培训教程(含课程源代码)

    讲解ajax的工作原理和实例全国省市区3级联动01-ajax概要和第一个示例02-AJAX 工作原理03-创建 XMLHttpRequest 对象04-使用phpstorm工具来开发05-Get方法和读取中文乱码解决06-Post方法和小坑的解决07-XMLHttpRequest...

    ajax文档ajax文档

     Ajax的核心是JavaScript对象XmlHttpRequest。该对象在Internet Explorer 5中首次引入,它是一种支持异步请求的技术。简而言之,XmlHttpRequest使您可以使用JavaScript向服务器提出请求并处理响应,而不阻塞用户。

    4天学会ajax XMLHttpRequest

    本文的作者是一位 Ajax 专家,他演示了这些技术如何协同工作 —— 从总体...他还揭开了 Ajax 核心概念的神秘面纱,包括 XMLHttpRequest 对象。作者对ajax做了深入浅出讲解,很适合初学者学习,在这里和大家共同分享了。

    简单谈谈AJAX核心对象

     Ajax的核心理念在于使用XMLHttpRequest对象发送异步请求.Ajax并不是一门新的语言或技术,它实际上是几项技术按一定的方式组合在一起,共同的协作中发挥各自的作用.  Ajax的优点  1.减轻服务器的负担.Ajax的原则是...

    Ajax核心XMLHttpRequest总结

    Ajax:即”Asynchronous JavaScript and XML”(异步JavaScript和XML),一门综合性的技术:运用JavaScript对象XMLHttpRequest进行异步数据交换;JavaScript操作DOM实现动态效果;运用XHTML+CSS表达信息;XML和XSLT...

    AJAX XMLHttpRequest对象详解

    其核心是XMLHttpRequest对象,可以在不向服务器端提交整个页面的情况下,实现局部更新网页,它是AJAX的Web应用程序架构的一项关键技术。 基本属性: 基本方法: XMLHttpRequest五步法:  第一:创建...

    基于J2EE的Ajax宝典

    本书介绍的内容非常全面,覆盖了Ajax技术的各个方面,包括Ajax技术的核心对象XMLHttpRequest对象、JavaScript脚本的详细知识以及DOM和XML的相关知识。除了Ajax的这些基础知识外,本书还详细介绍了Ajax的5个相关框架...

    《锋利的jQuery》(高清扫描版-有书签)

    第1篇介绍了jQuery中的$(document).ready...第3篇介绍了Ajax的核心对象---XMLHttpRequest. 第4篇介绍了jQuery中的$.ajax()方法. 第5篇介绍了jQuery加载并解析xml. 第6篇是第七章的插件的API 第7篇是jQuery API速查表.

Global site tag (gtag.js) - Google Analytics