XMLHttpRequest 从远程主机获取 HTTP 响应 [英] XMLHttpRequest to get HTTP response from remote host
问题描述
为什么以下代码 基于 Mozilla 示例不起作用?尝试使用 Firefox 3.5.7 &铬.
Why the following code Based on Mozilla example does not work? Tried with Firefox 3.5.7 & Chrome.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
</head>
<body>
</body>
<script>
var req = new XMLHttpRequest();
req.open('GET', 'http://www.mozilla.org/', false);
req.send();
if(req.status == 200) {
alert(req.responseText);
}
</script>
</html>
请确保浏览器正在从本地磁盘中提取 html (file:///C:/Users/Maxim%20Veksler/Desktop/XMLHTTP.html)
Please that the browser is pulling the html from local disk (file:///C:/Users/Maxim%20Veksler/Desktop/XMLHTTP.html)
在 Firefox 上,它给出以下错误:
On Firefox it gives the following error:
uncaught exception: [Exception... "Component returned failure code: 0x80004005 (NS_ERROR_FAILURE) [nsIXMLHttpRequest.send]" nsresult: "0x80004005 (NS_ERROR_FAILURE)" location: "JS frame :: file:///C:/Users/Maxim%20Veksler/Desktop/XMLHTTP.html :: <TOP_LEVEL> :: line 10" data: no]
我做错了什么?我想向远程主机提交请求并提醒结果(稍后添加到 div 中).
What am I doing wrong? I want to submit a request to remote host and alert the result (later to added into a div).
推荐答案
您的浏览器正在阻止 cross-站点脚本.您必须使用相对路径,否则大多数浏览器只会返回错误或空的 responseText.
Your browser is preventing cross-site scripting. You have to use a relative path, otherwise most browsers will simply return an error or an empty responseText.
以下 Stack Overflow 帖子可能也与您的问题有关:
The following Stack Overflow post is probably also related to your problem:
这篇关于XMLHttpRequest 从远程主机获取 HTTP 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!