2014-03-03 42 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/