2014-03-03 43 views
5

我有這個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> 
+1

跨域請求只是[默認情況下不允許](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之間的請求。 –

回答

5

如果Access-Control-Allow-Origin頭響應頭設置datafile.php工程:)

+0

是的謝謝你,但我沒有訪問datafile.php:/ – tomsk

+0

這是不可能的:(跨域目標文件(服務器)應該允許來自你的域的請求 –

+0

它必須存在的東西允許顯示來自外部頁面的文本 – tomsk

1

您可以發送請求到服務器,然後將其重定向到任何你想要的:

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] 

JavaScript函數將把example.com中的響應寫入txtHint div中。

我這樣寫,因爲這是我在我的應用程序中使用它,所以我只做了小改動。 希望它有幫助

-1

你不能做跨域請求,由於客戶端(瀏覽器)中的安全問題,從example1.com到example2.com通過XMLHttpRequest或jQuery(這是XMLHttpRequest的包裝)。這可以在現代瀏覽器中通過CORS支持HTML5(跨源資源共享,它不能在每個客戶端瀏覽器中都可用)有效地實現。 因此,解決方案是在example2.com的example1.com中插入腳本標記,此解決方案是稱爲JSON-P(帶填充的JSON),名稱可能會引起誤解,因爲數據可以採用服務器提供的任何格式(example2.com)。其實施代碼在此鏈接中給出http://newtechinfo.net/jsonp-for-cross-domain-ajax/