简体   繁体   English

W3Schools无法复制tryit编辑器

[英]W3Schools unable to replicate tryit editor

I was testing some code on the tryit editor and was unable to replicate functionality when I save the code locally and was wondering it anyone had any ideas as to why this seems to happen. 我在tryit编辑器上测试了一些代码,但是当我将代码保存在本地时无法复制功能,并且想知道为什么有人对此有任何想法。

The code snippet is 该代码段是

<html>
<head>
<script type="text/javascript" src="http://www.w3schools.com/dom/loadxmldoc.js"></script>
</head>
<body>  
<script type="text/javascript">
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
for (j=0;j<xmlDoc.getElementsByTagName("book").length;j++ )
{
    x=xmlDoc.getElementsByTagName("book")[j].childNodes;
    y=xmlDoc.getElementsByTagName("book")[j].firstChild;
    for (i=0;i<x.length;i++)
    {
        if (y.nodeType==1)  
        {
            //Process only element nodes (type 1)  
            document.write(y.nodeName + " : " +x[i].childNodes[0].nodeValue + "<br />");  
        }
        y=y.nextSibling;
    }
}
</script>
</body>
</html>

Can someone tell me what I'm doing wrong here 有人可以告诉我我在做什么错

Many thanks in advance 提前谢谢了

Edit: Thanks to all for the w3schools tip. 编辑:感谢所有w3schools提示。 I think I abuse the tryit more than I should stop doing so 我认为我滥用锥虫的次数比我应该停止的更多

The loadXMLDoc() w3schools provides uses XMLHttpRequest behind the scenes, which is restricted the Same Origin Policy. w3schools的loadXMLDoc()幕后提供了XMLHttpRequest的使用,这限制了Same Origin Policy。 (SOP) (标准操作程序)

The SOP states you can only make requests to resources on the same domain. SOP声明您只能对同一域上的资源发出请求。

When you save the file locally, you're no longer on the w3schools domain and so can't access files on it. 在本地保存文件时,您将不再位于w3schools域中,因此无法访问该文件。

function loadXMLDoc(dname) {
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
}​

You are probably running into the same origin policy here. 您可能在此处遇到了相同的原始策略。

Try saving the XML-file locally and load it from there instead of the remote server of w3schools. 尝试将XML文件保存在本地并从那里加载,而不是从w3schools的远程服务器加载。

First thing first, you should avoid using w3schools as your reference http://w3fools.com 首先,您应该避免使用w3schools作为参考http://w3fools.com

Second, you can't do that as loadXMLDoc is using AJAX and you can't request document in different domain using AJAX (Unless you use JSONP, but that's another subject altogether) 其次,您不能这样做,因为loadXMLDoc使用的是AJAX,也不能使用AJAX来请求其他域中的文档(除非您使用JSONP,但这是另一个主题)

http://en.wikipedia.org/wiki/Same_origin_policy http://en.wikipedia.org/wiki/Same_origin_policy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM