我有这个JavaScript代码从页面提取文本,它工作正常,如果我打开文件在我的域名,但我不能从另一个域中的文件中获取文本,因为一些安全原因。所以我的问题是我怎么可以请从另一个网站在JavaScript中提取文本,请不jquery。XMLHttpRequest跨域
谢谢
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>
跨域请求只是[默认情况下不允许](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Same_origin_policy_for_JavaScript)。远程服务器可以通过[CORS](https:/ /developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS),或支持[JSONP](http://en.wikipedia.org/wiki/JSONP)等Ajax选项,但如果使用'datafile.php'不提供任何这些功能,那么您需要创建自己的服务器端层来调解浏览器和anotherweb.com之间的请求。 –