Safari问题,变量未定义(XML / Javascript)

时间:2014-06-30 11:36:21

标签: javascript php html xml safari

我有这段代码,它适用于除Safari以外的所有浏览器:

        // Create a connection to the file.
        var Connect = new XMLHttpRequest();

        // Define which file to open and
        // send the request.
        Connect.open("GET", "<?php echo $fileName;?>", false);
        Connect.setRequestHeader("Content-Type", "text/xml");
        Connect.setRequestHeader("Cache-Control", "no-cache");
        Connect.send();

        // Place the response in an XML document.
        var TheDocument = Connect.responseXML;

        // Place the root node in an element.
        var questions = TheDocument.childNodes[0];

        // Retrieve each customer in turn.
        for (var i = 0; i < 1; i++) {
            console.log(i);
            console.log("fake var");
            var question = questions.children[0];
            console.log(question);
        }

Variable $ filename是我读取的XML文件的php链接。 我有以下问题,代码运行到For循环,我可以记录var&#34; i&#34;和&#34;假var&#34;。但是一旦我将var问题定义为questions.children [0],代码就会停止。我无法在safari中记录问题var。

有什么想法吗? (反馈也欢迎,仍在学习javascript / xml)

我的XML示例:

<?xml version='1.0' encoding="UTF-8" ?>
<Beantwoordt_kritiek id="1" admin="Jan Hut" categorie="Omgaan met elkaar" winswf="images/Kado (1).jpg">
  <gebruikers_vraag1>
    <vraag><![CDATA[Sleep de puzzelstukken naar het juiste vakje.]]></vraag>
    <s_vraag><![CDATA[sounds/puzzel.mp3]]></s_vraag>
    <thumb1><![CDATA[images/527puzzel1_1.jpg]]></thumb1>
    <thumb2><![CDATA[images/527puzzel1_2.jpg]]></thumb2>
    <thumb3><![CDATA[images/527puzzel1_3.jpg]]></thumb3>
    <thumb4><![CDATA[images/527puzzel1_4.jpg]]></thumb4>
    <vraagFoto><![CDATA[images/527puzzel1.jpg]]></vraagFoto>
  </gebruikers_vraag1>
</Beantwoordt_kritiek>

1 个答案:

答案 0 :(得分:1)

您可以使用此脚本,因此safari会返回相同的结果。

<script>
function getChildren(element) {
  if (element.children == undefined) {
    var childNodes = element.childNodes
    var children = []
    for(var i = 1; i < childNodes.length; i += 2) {  // take every second element
      children.push(childNodes[i]);
    }
    return children;
  } else {
    return element.children
  }
}
</script>

然后在脚本中调用它

var question = getChildren(questions)[0];