XMLHttpRequest跨域

tom*_*msk 7 javascript response xmlhttprequest cross-domain

我有这个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);
Run Code Online (Sandbox Code Playgroud)

我尝试过这个并没有用.

<!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>
Run Code Online (Sandbox Code Playgroud)

Pru*_*lli 8

如果 Access-Control-Allow-Origindatafile.php它的响应标头中设置了标头,则工作:)