gpt4 book ai didi

javascript - XMLHttpRequest 请求出现问题

转载 作者:行者123 更新时间:2023-11-28 08:28:48 26 4
gpt4 key购买 nike

我有 html 页面使用 ajax 从另一个页面提取数据。

该代码在 Firefox 上运行良好,但在 IE 和 Chrome 中的 xhr.open("...") 上拒绝访问。

示例代码如图所示。

<!DOCTYPE html>
<html>
<head>
<script type="text/Javascript">
function changeContent(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",url,false); //Access denied on this line
xhr.send();
var roster = document.getElementById("roster");
roster.innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<img src=images/logo_990x80.png width=1300" height="80" />

<div class="buttonBar">
<input type="button" value="data" onclick="changeContent('data.html')"/>
</div>

<div id="roster" class="roster">
Click on the buttons above to choose a roster
</div>

</body>
</html>

data.html 包含一个包含 2 行数据的简单表格。

如何解决这个问题。

编辑:下面显示的代码适用于 IE 和 Firefox,但在 Chrome 中仍然存在相同的问题。ActiveX 似乎适用于 Ajax 的本地文件。

<!DOCTYPE html>
<html>
<head>
<script type="text/Javascript">
function changeContent(url)
{
var xhr = false;
if(location.protocol=="file:")
{
if(!xhr)try{ xhr=new ActiveXObject("MSXML2.XMLHTTP"); }catch(e){xhr=false;}
if(!xhr)try{ xhr=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){xhr=false;}
}
else
{
if(!xhr)try{ xhr=new XMLHttpRequest(); }catch(e){xhr=false;}
}
xhr.open("GET",url,false); //Access denied on this line only in Chrome
xhr.send();
var roster = document.getElementById("roster");
roster.innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<img src=images/logo_990x80.png width=1300" height="80" />

<div class="buttonBar">
<input type="button" value="data" onclick="changeContent('data.html')"/>
</div>

<div id="roster" class="roster">
Click on the buttons above to choose a roster
</div>

</body>
</html>

有关 Chrome 的任何提示。

最佳答案

这通常是由于尝试使用 XMLHTTPRequest 而不使用 HTTP URI 引起的。

Firefox 通过 file: 方案 URI 支持 XHR,但大多数浏览器不支持。

如果您想使用 Ajax,请通过 Web 服务器运行您的页面。

关于javascript - XMLHttpRequest 请求出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22096329/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com