Ajax當中給出一個helloWorld例子

1.helloWorld
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例 1.1(testIEFF.htm)





<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>helloworld</title>
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
    if(window.ActiveXObject){//ie
        alert("we are using microsoft ActiveXObject");
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest();
    }
}

function startRequest(){

    createXMLHttpRequest();
/*
馬克-to-win:onreadystatechange: 指定當readyState屬性改變時的事件處理句柄

  每當XMLHttpRequest狀態(tài)改變時,onreadystatechange事件就觸發(fā),
actually, the next statement won't be immidiately executed, it just determine that when the status
changes, it will run handleStateChange.
  */
    xmlHttp.onreadystatechange = handleStateChange;
/* open()的第一個參數(shù)是HTTP請求方式 GET, POST, HEAD 或任何服務(wù)器所支持的您想調(diào)用的方式.
馬克-to-win: it will go to the same webmodule to get "servlet", or
you can xmlHttp.open('GET', 'http://www.example.org/some.file', true);
第二個參數(shù)是請求頁面的URL. 第三個參數(shù)設(shè)置請求是否為異步模式.如果是TRUE, JavaScript函數(shù)將繼續(xù)執(zhí)行,而不等待服務(wù)器響應(yīng).
這就是"AJAX"中的"A".
*/
/*下面兩句都可以工作,但1.txt處理不了中文,下面參數(shù)q不能為中文    */
    xmlHttp.open("GET","servlet11?q=mark",true);
// xmlHttp.open("GET","1.txt",true);
/*如果第一個參數(shù)是"POST",send()方法的參數(shù)可以是任何想送給服務(wù)器的數(shù)據(jù). 這時數(shù)據(jù)要以字符串的形式
送給服務(wù)器,如下所示: name=value&anothername=othervalue&so=on
*/
    xmlHttp.send(null);
}
function handleStateChange(){
/*
馬克-to-win:readyState: 返回XMLHTTP請求的當前狀態(tài)
變量,此屬性只讀,狀態(tài)用長度為4的整型表示.定義如下:

0 (未初始化) 對象已建立,但是尚未初始化(尚未調(diào)用open方法)
1 (初始化) 對象已建立,尚未調(diào)用send方法
2 (發(fā)送數(shù)據(jù)) send方法已調(diào)用,但是當前的狀態(tài)及http頭未知
3 (數(shù)據(jù)傳送中) 已接收部分數(shù)據(jù),因為響應(yīng)及http頭不全,這時通過responseBody和responseText獲取部分數(shù)據(jù)會出現(xiàn)錯誤,
4 (完成) 數(shù)據(jù)接收完畢,此時可以通過通responseText獲取完整的回應(yīng)數(shù)據(jù)
*/
    if(xmlHttp.readyState == 4){
/*
status: 長整形標準http狀態(tài)碼,此屬性僅當數(shù)據(jù)發(fā)送并接收完畢后才可獲取。定義如下: Number  Description
500 Internal Server Error
200 OK
404 Not Found
504 Gateway Timeout
*/
        if(xmlHttp.status == 200){//成功得到請求內(nèi)容
            var tex=xmlHttp.responseText;
            alert(tex);
            document.getElementById("results").innerHTML = tex;
        }
    }
}
</script>
</head>
<body>
<form>
    <input type="button" value="Start info Request" onClick="startRequest();" />
</form>
<hr>
以下是請求內(nèi)容:
<div id="results"></div>
</body>
</html>

servlet11.java





package helloWorld;

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


public class servlet11 extends HttpServlet {
    private static final String CONTENT_TYPE = "text/html; charset=GBK";

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              response.setContentType(CONTENT_TYPE);
        String s=null;
        PrintWriter out = response.getWriter();
   if(request.getParameter("q")!=null)
       {
           s=request.getParameter("q");
       }
        out.println("<p>這是馬克-to-win 的一個測試用例, 中文能回顯<br>,因為xmlHttp用的是xmlHttp.responseText<br>"
                    +s+"接受信息,所以response.setContentType(\"text/html; charset=GBK\");"+"\nbcd\ncde"
                    );

        out.close();
    }
}






例 1.2(test1IEFF.htm)

1.txt
this is a test, can not be chinese,only can be pure data
例 1.2(test3_5XMLFF&IE.htm)

<html>
<body>
    <table width="95%" border="4" align="center">
        <tr>
            <td>標題</td>
            <td>作者</td>
        </tr>
        <tbody id="display">
        </tbody>
    </table>
</body>
</html>
<script type="text/javascript">
    function makeRequest(url) {
        if (window.ActiveXObject) {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } else if (window.XMLHttpRequest) {
            http_request = new XMLHttpRequest();
        }
        http_request.onreadystatechange = alertContents;
        http_request.open('GET', url, true);
        http_request.send(null);
    }
    function alertContents() {
        if (http_request.readyState == 4) {
            if (http_request.status == 200) {
                var xmldoc = http_request.responseXML;
*注意下面這句話中是區(qū)分大小寫的*/              
                var root_node = xmldoc.getElementsByTagName('BOOKS').item(0);
                var root = xmldoc.documentElement;
                alert("root.tagName is "+root.tagName+"root_node.tagName is "+root_node.tagName);

                var tChil=root.children;
                alert(tChil.length+"tChil[1].tagName is "+tChil[1].tagName);
                var tChilChil=tChil[1].children;
                alert(tChilChil[1].firstChild.nodeValue);
                var aContent = xmldoc.getElementsByTagName("COMPUTERBOOK");
                for ( var i = 0; i < aContent.length; i++) {
/*馬克-to-win:既然沒有g(shù)etSingleElementByTagName,我們就用getElementsByTagName()[0],
xmldoc.getElementsByTagName("TITLE")[0].firstChild.nodeValue
這種方法雖然略顯得笨拙,但是他能夠達到兼容的效果。
*/
                    var data = [ xmldoc.getElementsByTagName("TITLE")[i].firstChild.nodeValue,xmldoc.getElementsByTagName("ARTIST")[i].firstChild.nodeValue];
                    var newRow = createRow(data);
                    var displayTable = document.getElementById("display");
                    displayTable.appendChild(newRow)
                }

            } else {
                alert('There was a problem with the request.');
            }
        }

    }

    root = makeRequest("book.xml");

    function createRow(data) {
        var row, cell, txtNode;
        row = document.createElement("tr");
        for ( var i = 0; i < data.length; i++) {
            cell = document.createElement("td");
/*the following two statements's function is the same as the third statement. we can use either way to achieve goal.*/
            //    txtNode = document.createTextNode(data[i]);
            //    cell.appendChild(txtNode);
            cell.innerHTML = data[i];
            row.appendChild(cell);
        }
        return row;
    }
</script>



book.xml



<?xml version="1.0" ?>
<BOOKS>
    <COMPUTERBOOK>
        <TITLE>java</TITLE>
        <ARTIST>馬克-to-win:</ARTIST>
    </COMPUTERBOOK>
    <COMPUTERBOOK>
        <TITLE>javascript</TITLE>
        <ARTIST>馬克-to-win:開</ARTIST>
    </COMPUTERBOOK>
</BOOKS>