Ajax:一种网页开发技术(Asynchronous Javascript + XML)

  1. 创建新的 XMLHttpRequest 对象(Ajax 应用程序的核心):
    <script language="javascript" type="text/javascript">
        var xmlHttp = new XMLHttpRequest();
    </script>
  2. 用 JavaScript 代码捕获和设置字段值
    //获取 id 值为 first_name 的表单域
    var name = document.getElementById('first_name').value;
    
    //修改 id 值为 test 的表单域的值
    document.getElementById('test').value = response[0];
    

      

  3. 在 Microsoft 浏览器上创建 XMLHttpRequest 对象
    var xmlHttp = false;
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        xmlHttp = false;
      }
    }
    

      

  4. 以支持多种浏览器的方式创建 XMLHttpRequest 对象
    /* Create a new XMLHttpRequest object to talk to the Web server */
    var xmlHttp = false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    try {
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e2) {
        xmlHttp = false;
      }
    }
    @end @*/
    
    if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
      xmlHttp = new XMLHttpRequest();
    }
    

      

  5. 开始工作:发送Ajax请求
    function callServer() {
      // Get the city and state from the web form
      var city   = document.getElementById("city").value;
      var state = document.getElementById("state").value;
    
      // 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);
    }
    

      

posted @ 2015-11-20 17:09  陈教授Aston  阅读(172)  评论(0)    收藏  举报