2012年11月7日 星期三

Ajax

簡單的ajax物件

var xmlHttp;
function createXMLHttpRequest(){
  if(window.ActiveXObject){
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }else if (window.XMLHttpReqeust){
    xmlHttp=new XMLHttpRequest();
  }
}
基本的屬性跟方法有
abort()
getAllResponseHeaders()
getResponseHeader("header")
open("method","url", asynch, username, password)
send(content)
setRequestHeader("header","value")
<script type="text/javascript" language="javascript">
  // 修改自 AJAX: Getting Started - MDC
  function makeRequest(url) {
    var http_request = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
          http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
    }

    if (!http_request) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    // 定義事件處理函數為 alterContents()
    http_request.onreadystatechange = function() { 
                                      alertContents(http_request); };
    http_request.open('GET', url, true);
    http_request.send(null);
  }

  function alertContents(http_request) {
    if (http_request.readyState == 4) {
      if (http_request.status == 200) {
        var xmldoc = http_request.responseXML;
        var nodes = xmldoc.getElementsByTagName('area');
        var mesg = "";
        for(var i=0; i<nodes.length; i  ) {
          mesg  = nodes[i].firstChild.nodeValue   "\n";
        }
        //alert(mesg);
        document.getElementById("taichung").innerHTML = mesg;
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
</script>
參考資料:
  http://web.nchu.edu.tw/~jlu/classes/xml/ajax/example1.shtml

沒有留言:

張貼留言