2

オンラインxmlファイル( http://data.one.gov.hk/others/td/speedmap.xmlなど)からデータを取得したいと思います。HTMLからローカルで(サーブレットなしで)javascriptを呼び出すと機能します。ただし、jspとjavaサーブレットを介して呼び出すと機能しません。オンラインxmlファイルからデータを取得できるような別の方法はありますか?

contentXML.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <p>CONTENT_XML</p>

        <%@ include file="source_file/js_workable.js" %>
        <%@ include file="source_file/data_retrieve.js" %>

    </body>
</html>

data_retrieve.js

<script  LANGUAGE="JavaScript">


         if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
           xmlhttp=new XMLHttpRequest();
         }
         else { // code for IE6, IE5
           xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
         }

         document.write(xmlhttp.status);
         document.write(xmlhttp.readyState);
         document.write(xmlhttp.statusText);

         xmlhttp.open("GET","http://data.one.gov.hk/others/td/speedmap.xml",false);
         xmlhttp.send(); 


         xmlDoc=xmlhttp.responseXML; 

         document.write("<table border='1'>");
         var x=xmlDoc.getElementsByTagName("jtis_speedmap");
         for (i=0;i<x.length;i++){ 
           document.write("<tr><td>");
           document.write(x[i].getElementsByTagName("LINK_ID")[0].childNodes[0].nodeValue);
           document.write("</td><td>");
           document.write(x[i].getElementsByTagName("ROAD_TYPE")[0].childNodes[0].nodeValue);
           document.write("</td></tr>");
         }
         document.write("</table>");

</script>

htmlファイル:

<html>
 <body>

<script>
 if (window.XMLHttpRequest)
   {// code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp=new XMLHttpRequest();
   }
 else
   {// code for IE6, IE5
   xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
 xmlhttp.open("GET","http://data.one.gov.hk/others/td/speedmap.xml",false);
 xmlhttp.send();
 xmlDoc=xmlhttp.responseXML; 

document.write("<table border='1'>");
 var x=xmlDoc.getElementsByTagName("jtis_speedmap");
 for (i=0;i<x.length;i++)
   { 
  document.write("<tr><td>");
   document.write(x[i].getElementsByTagName("LINK_ID")[0].childNodes[0].nodeValue);
   document.write("</td><td>");
   document.write(x[i].getElementsByTagName("ROAD_TYPE")[0].childNodes[0].nodeValue);
   document.write("</td></tr>");
   }
 document.write("</table>");
 </script>

</body>
</html>
4

1 に答える 1

3

これはクロスドメインajaxリクエストであるため、Access-Control-Allow-Originルールによってブロックされました。

ソリューションでは、jsp /サーブレットを使用してHTTPリクエストを作成し、最初にXMLコンテンツを取得してから、ローカルでajaxリクエストを実行してjavascriptを実行します。

于 2013-01-14T04:02:13.870 に答える