是什么阻止我使用 $.ajax 加载另一个域的 html? [英] What prevents me from using $.ajax to load another domain's html?
问题描述
我的域:
<!DOCTYPE html>
<html>
<head>
<title>scrape</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({url:'http://their-domain.com/index.html',
dataType:'html',
success:function(data){console.log(data);}
});
</script>
</body>
</html>
是什么阻止我抓取他们的域名?有什么解决办法吗?
What prevents me from being able to scrape their-domain? Any work around?
附录:感谢大家对使用服务器端脚本的建议,但我目前对仅使用客户端解决这个问题感兴趣.
Addendum: thank you all for the suggestions to use a server side script, but I am for the moment interested in solving this problem exclusively using the client.
如果我使用jsonp"格式化请求,我至少会收到响应,但会出现以下错误:Uncaught SyntaxError: Unexpected token <".所以我得到了他们域的响应,但解析器希望它是 json.(也应该如此.)我正在通过这个尝试查看它们是否是一种诱使客户接受此响应的方法.请理解我知道这是不典型的.
If I format the request using "jsonp" I do at least get a response, but with the following error:"Uncaught SyntaxError: Unexpected token <". So I am getting a response from their-domain but the parser expects it to be json. (As well it should.) I am hacking through this trying to see if their is a way to trick the client into accepting this response. Please understand that I know this is atypical.
<!DOCTYPE html>
<html>
<head>
<title>scrape</title>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<script>
$.ajax({url:'http://their-domain.com/index.html',
dataType:'jsonp',
success:function(data){console.log(data);}
});
</script>
</body>
</html>
推荐答案
有四种方法可以解决同样的问题原产地政策
- 代理 - 你从你的服务器请求它,你的服务器从其他域请求它,你的服务器将它返回给浏览器
- Flash 跨域策略 - 其他域必须添加 crossdomain.xml 文件到他们的网站
- 跨域 HTTP 标头 -其他域必须在其页面中添加
Access-Control-Allow-Origin
标头 - JSONP - 这是一个提供回调函数的 json 网络服务.其他域必须实现这一点.
- Proxy - You request it from your server, your server requests it from other domain, your server returns it to the browser
- Flash cross domain policy - other domain must add a crossdomain.xml file to their site
- Cross domain HTTP header - other domain must add an
Access-Control-Allow-Origin
header to their page - JSONP - It's a json web service that provides a callback function. Other domain must implement this.
注意:在没有其他域帮助的情况下唯一的方法是#1,通过您自己的服务器路由.
Note: The ONLY way to do it without the other domain's help is #1, routing it through your own server.
这篇关于是什么阻止我使用 $.ajax 加载另一个域的 html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!