XMLHttpRequest 跨域问题

12

我有一段JavaScript代码,可以从页面中提取文本,在我的域名下打开文件时可以正常工作,但是在另一个域名下无法获取文件中的文本,因为存在安全原因。所以我的问题是如何在JavaScript中从另一个网站提取文本,而不使用jQuery。

谢谢

function reqListener () {
  console.log(this.responseText);
}

var xhr = new XMLHttpRequest();

xhr.onload = reqListener;

xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        alert(xhr.responseText);
    }
}
xhr.open('GET', 'http://anotherweb.com/datafile.php', true);
xhr.setRequestHeader('Content-Type', 'text/plain');
xhr.send(null);

我尝试了这个,但它不起作用。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">

$(document).ready(function(){
  $("button").click(function(){
    $.ajax({
      url: "http://localhost/index.php",
      dataType : "json",
      contentType: "application/json; charset=utf-8",
      cache: false,
      success: function(response) {
        alert(response);
      },
      error: function (e) {                
      }
      });
  });
});
</script>
</head>
<body>
<button>Send an HTTP GET request to a page and get the result back</button>
</body>
</html>

2
跨域请求默认是不允许的。远程服务器可以通过CORS或支持Ajax替代方案(如JSONP)向您的应用程序提供权限。但是,如果datafile.php没有提供任何这些内容,则需要创建自己的服务器端层来调解浏览器和anotherweb.com之间的请求。 - Jonathan Lonowski
4个回答

11

如果在datafile.php的响应头中设置了Access-Control-Allow-Origin标头,则它可以正常工作:)


是的,谢谢你,但我没有访问datafile.php的权限 :/ - tomsk
必须存在某种东西,可以显示来自外部页面的文本。 - tomsk
任何现代浏览器都无法进行跨域获取text/html。目前我知道的唯一可行的返回类型是jsonp。 - Pruthvi Raj Nadimpalli
@tomsk 这个回答解决了你的问题吗? - Pruthvi Raj Nadimpalli
1
这是我添加的,而且非常有效:header("access-control-allow-origin: *"); - Sileria
显示剩余2条评论

2
你可以将请求发送回服务器,然后将其重定向到任何你想要的地方:
JavaScript函数:
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();}
else{// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;}}
xmlhttp.open("POST","response.php",true);
xmlhttp.send();

.htaccess文件:

Options +FollowSymLinks
RewriteEngine On
RewriteRule  ^response(.*?)\.php http://example.com/query [R]

1

-2

由于客户端(浏览器)的安全问题,您无法通过XMLHttpRequest或jQuery(它是XMLHttpRequest的包装器)进行跨域请求,例如从example1.com到example2.com。这可以在支持HTML5的现代浏览器中通过CORS(跨源资源共享)有效实现,但并非每个客户端浏览器都可用。

因此,解决方案是在example1.com中插入example2.com的脚本标记,这个解决方案称为JSON-P(带填充的JSON),名称可能会误导,因为数据可以是由服务器提供的任何格式(例如example2.com)。其实现代码在此链接中给出http://newtechinfo.net/jsonp-for-cross-domain-ajax/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接