1. 程式人生 > >從零開始的畢設--JavaScript-Ajax(2)-GET

從零開始的畢設--JavaScript-Ajax(2)-GET

DOM處理XML

XML在伺服器記錄的內容,在用GET方法傳回客戶端時,DOM可以把XML當成節點樹處理。 我們的blog.xml檔案是這樣的:

<?xml version="1.0" encoding="utf-8"?>
<blog>
  <title>YouCube - The Blog for Cube Puzzlers</title>
  <author>Puzzler Ruby</author>
  <entries>
    <entry>
      <date>08/14/2008</
date
>
<body>Got the new cube I ordered. It's a real pearl.</body> </entry> <entry> <date>08/19/2008</date> <body>Solved the new cube but of course, now I'm bored and shopping for a new one.</body> </entry> <entry>
<date>08/16/2008</date> <body>Managed to get a headache toiling over the new cube. Gotta nap.</body> </entry> <entry> <date>08/21/2008</date> <body>Found a 7x7x7 cube for sale online. Yikes! That one could be a beast.</body>
</entry> <entry> <date>08/29/2008</date> <body>Met up with some fellow cubers to discuss the prospect of a 7x7x7 cube. Mixed feelings.</body> </entry> <entry> <date>08/27/2008</date> <body>Went ahead and ordered the scary 7x7x7 cube. Starting a mental exercise regimen to prepare.</body> </entry> <entry> <date>09/3/2008</date> <body>Attended a rally outside of a local toy store that stopped carrying cube puzzles. Power to the puzzlers!</body> </entry> <entry> <date>09/5/2008</date> <body>Got the new 7x7x7 cube. Could be my last blog post for a while...</body> </entry> <entry> <date>09/19/2008</date> <body>Wow, it took me a month but the new cube is finally solved!</body> <image>cube777.png</image> </entry> <entry> <date>09/24/2008</date> <body>I dreamed last night a huge cube was chasing me, and it kept yelling my name backwards...Ybur!</body> </entry> <entry> <date>09/26/2008</date> <body>These dreams just keep getting weirder...now I'm seeing a cube take itself apart. What <strong>does</strong> it mean?</body> <image>cubeapart.png</image> </entry> </entries> </blog>
function getText(elem) {
//elem自變數是欲提取內容的元素的名稱
        var text = "";
        if (elem) {
          if (elem.childNodes) {
            for (var i = 0; i < elem.childNodes.length; i++) {
            //通過迴圈,獲取elem的子節點
              var child = elem.childNodes[i];
              if (child.nodeValue)//如果子節點是根節點
                text += child.nodeValue;
              else {  
                if (child.childNodes[0])//如果子節點還有子節點
                  if (child.childNodes[0].nodeValue)//如果孫子節點是根節點
                    text += child.childNodes[0].nodeValue;//取子節點的第一個節點即可。
              }
            }
          }
        }
        return text;
      }

假設XML響應資料已經全部儲存在變數xmlData中,如果要使用xml標籤<author>

Blog.prototype.signature="by"+getText(xmlData.getElementByTagName("author")[0]);

最後Handler的程式碼:

  // Handle the Ajax request
      function handleRequest() {
        if (ajaxReq.getReadyState() == 4 && ajaxReq.getStatus() == 200) {
          // Store the XML response data
          var xmlData = ajaxReq.getResponseXML().getElementsByTagName("blog")[0];

          // Set the blog-wide signature
          Blog.prototype.signature = "by " + getText(xmlData.getElementsByTagName("author")[0]);


          // Create the array of Blog entry objects
          var entries = xmlData.getElementsByTagName("entry");
          for (var i = 0; i < entries.length; i++) {
            // Create the blog entry
            blog.push(new Blog(getText(entries[i].getElementsByTagName("body")[0]),
              new Date(getText(entries[i].getElementsByTagName("date")[0])),
              getText(entries[i].getElementsByTagName("image")[0])));
          }

          // Enable the blog buttons
          document.getElementById("search").disabled = false;
          document.getElementById("showall").disabled = false;
          document.getElementById("viewrandom").disabled = false;

          // Show the blog
          showBlog(5);
        }else {
          alert(ajaxReq.getReadyState()+" :"+ajaxReq.getStatus());
        }
      }