use*_*665 19 javascript cross-domain
如何在用户的浏览器中使用JavaScript向其他服务器发出请求(即从任何所需服务器获取页面)?对于像XMLHttpRequest这样的方法,有什么限制可以阻止这种情况,有没有办法绕过它们或其他方法?
这是一个普遍的问题,特别是我想检查一系列随机网站并查看它们是否包含某个元素,因此我需要网站的HTML内容而不下载任何其他文件; 所有这些都在JavaScript文件中,在服务器上没有任何转发或代理机制.
(注意:一种方法是使用Greasemonkey及其GM_xmlhttpRequest.)
Sam*_*son 22
你应该看看jQuery.它具有丰富的AJAX功能,可以让您完成所有这些功能.您可以加载外部页面,并使用直观的类似CSS的选择器解析它的HTML内容.
使用$ .get()的示例;
$.get("anotherPage.html", {}, function(results){
alert(results); // will show the HTML from anotherPage.html
alert($(results).find("div.scores").html()); // show "scores" div in results
});
Run Code Online (Sandbox Code Playgroud)
对于外部域,我必须编写一个本地PHP脚本,作为中间人.jQuery将调用本地PHP脚本传入另一个服务器的URL作为参数,本地PHP脚本将收集数据,jQuery将从本地PHP脚本读取数据.
$.get("middleman.php", {"site":"http://www.google.com"}, function(results){
alert(results); // middleman gives Google's HTML to jQuery
});
Run Code Online (Sandbox Code Playgroud)
给middleman.php一些东西
<?php
// Do not use as-is, this is only an example.
// $_GET["site"] set by jQuery as "http://www.google.com"
print file_get_contents($_GET["site"]);
?>
Run Code Online (Sandbox Code Playgroud)
2018 年更新:
您只能在以下4个条件下访问跨域
Access-Control-Allow-Origin: *演示
$.ajax({
url: 'https://api.myjson.com/bins/bq6eu',
success: function(response){
console.log(response.string);
},
error: function(response){
console.log('server error');
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
演示:
$.ajax({
url: 'https://cors-anywhere.herokuapp.com/http://whatismyip.akamai.com/',
success: function(response){
console.log('server IP: ' + response);
},
error: function(response){
console.log('bridge server error');
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>Run Code Online (Sandbox Code Playgroud)
Allow-Control-Allow-Origin: *铬合金
chrome.exe --args --disable-web-security
Run Code Online (Sandbox Code Playgroud)
火狐
about:config -> security.fileuri.strict_origin_policy -> false
Run Code Online (Sandbox Code Playgroud)
结尾
菜鸟旧答案 2011
$.get(); 可以从jsbin.com获取数据,但我不知道为什么它不能从其他站点(如 google.com)获取数据
$.get('http://jsbin.com/ufotu5', {},
function(results){ alert(results);
});
Run Code Online (Sandbox Code Playgroud)
演示:http : //jsfiddle.net/Xj234/ 使用 firefox、chrome 和 safari 进行测试。
| 归档时间: |
|
| 查看次数: |
54830 次 |
| 最近记录: |