zoukankan      html  css  js  c++  java
  • XMLHttpRequest的三种版本切换和ajax的异步请求

     XMLHttpRequest的三种版本切换
    <script language="java script" type="text/java script">
    var request;
    function createRequest() {
    try {
    request = new XMLHttpRequest();
    } catch (trymicrosoft) {
    try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
    try {
    request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
    request = false;
    }
    }
    }
    if (!request)
    alert("Error initializing XMLHttpRequest!");
    }
    </script>
    1. 尝试创建 XMLHttpRequest 对象。
    2. 如果失败(catch (trymicrosoft)):
    1. 尝试使用较新版本的 Microsoft 浏览器创建 Microsoft 兼容的对象(Msxml2.
    XMLHTTP)。
    2. 如果失败(catch (othermicrosoft))尝试使用较老版本的 Microsoft 浏览器创建 Microsoft
    兼容的对象(Microsoft.XMLHTTP)。
     
     
    ajax的异步请求
    function callServer() {
    // Get the city and state from the web form
    var city = document.getElementById("city").value;
    var state = document.getElementById("state").value;
    // Only go on if there are values for both fields
    if ((city == null) || (city == "")) return;
    if ((state == null) || (state == "")) return;
    // Build the URL to connect to
    var url = "/scripts/getZipCode.php?city=" + escape(city) + "&state=" + escape(state);
    // Open a connection to the server
    xmlHttp.open("GET", url, true);
    // Setup a function for the server to run when it's done
    xmlHttp.onreadystatechange = updatePage;
    // Send the request
    xmlHttp.send(null);
    }
    ● open():建立到服务器的新请求。
    ● send():向服务器发送请求。
    ● abort():退出当前请求。
    ● readyState:提供当前 HTML 的就绪状态。
    ● responseText:服务器返回的请求响应文本。
     
    XMLHttpRequest.open中指定了连接方法(GET)和要连接的URL。最后一个参数如果设为 true,那么将请求一个异步连接(这就是 Ajax 的由来)。如果使用 false,那么代码发出请求后将等待服务器返回的响应。如果设为 true,当服务器在后台处理请求的时候用户仍然可以使用表单(甚至调用其他 java script 方法)。
     
    XMLHttpRequest 的 onreadystatechange 属性可以告诉服务器在运行完成后(可能要用五分钟或者五个小时)做什么。因为代码没有等待服务器,必须让服务器知道怎么做以便您能作出响应。在这个示例中,如果服务器处理完了请求,一个特殊的名为 updatePage() 的方法将被触发。
     
  • 相关阅读:
    ubuntu 13.04 root权限设置方法详解
    观锁和乐观锁——《POJOs in Action》
    观锁与悲观锁(Hibernate)
    关于python的环境变量问题
    vs2010 调试快捷键
    VIM7.3中文手册
    Java最全文件操作实例汇总
    response letter模板
    数据库字段类型
    Tomcat系列之Java技术详解
  • 原文地址:https://www.cnblogs.com/buyinji/p/2301272.html
Copyright © 2011-2022 走看看