我有這個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之間的請求。 –