AJAX 入門:第二個範例
The following examples had been tested on Mozilla's Firefox and Microsoft's IE. The document is provided as is. You are welcomed to use it for non-commercial purpose.Written by: 國立中興大學資管系呂瑞麟
請勿轉貼
看其他教材
在第一個範例中,為了簡化起見,我們只是將遠端的檔案下載下來,再經由 Javascript 的 DOM 功能來剖析 XML 文件。可是絕大多數的 AJAX 網頁都是 跟伺服器端的程式來做互動的,因此在第二個範例中,我們延續第一個範例, 差別只是在於這次我們呼叫的對象是伺服器端的程式,其他不變。 仔細檢查第一個範例的程式碼,我們發現在 HTML 元件的第一個 div 區塊,我們 利用
onclick="makeRequest('taichung.xml') 來啟動呼叫,而
taichung.xml 就變成了 makeRequest() 中的 url,而這個 url
變數的值就代表了伺服器的資源或者程式。我們可不可以使用之前非 AJAX 網頁中
所寫的 servlet 呢?嗯,試試看!讓我們簡單的將
onclick="makeRequest('taichung.xml')" 改成
onclick="makeRequest('http://xml.nchu.edu.tw/jlu/servlet/Taichung')"。(由於資安的理由,我們無法在這網頁執行,可以自行練習或者到 demo 網頁)
取得台中行政區域
另外,由於 servlet 回傳的是一個 HTML 檔,而不是一個 XML 檔,所以 alertContents() 並不需要處理 XML 的內容,而是直接接收即可,因此我們把它改成:
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var mesg = http_request.responseText;
//alert(mesg);
document.getElementById("taichung").innerHTML = mesg;
} else {
alert('There was a problem with the request.');
}
}
}
為了讓大家可以自行架站後測試,我特別把 Taichung.java 這個 servlet 的原始碼提供如下:
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.w3c.dom.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.net.*;
public class Taichung extends HttpServlet {
static Document document;
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html;charset=Big5");
PrintWriter output = res.getWriter();
StringBuffer buf = new StringBuffer();
buf.append("<html><head><title>\n");
buf.append("台中地區的行政區\n");
buf.append("</title></head><body>\n");
// 讀取 xml 檔
File file=new File(getServletContext().getRealPath("/")+"taichung.xml");
buf.append("<h1 align=\"center\">台中地區的行政區</h1>\n");
buf.append("<hr/>\n");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
document = db.parse(file);
NodeList nodes = document.getElementsByTagName("area");
for (int i=0 ; i < nodes.getLength(); i++) {
buf.append(nodes.item(i).getFirstChild().getNodeValue()+"<br/>\n");
}
buf.append("</body></html>\n");
output.println(buf.toString());
output.close();
} catch(SAXException se) {
Exception e = se;
if ( se.getException() != null )
e = se.getException();
e.printStackTrace();
} catch(ParserConfigurationException pe) {
pe.printStackTrace();
} catch(IOException ie) {
ie.printStackTrace();
}
}
}
Written by: 國立中興大學資管系呂瑞麟
沒有留言:
張貼留言