[英]How to get data with JavaScript from another server?
如何在用户的浏览器中使用JavaScript向其他服务器发出请求(即从任何所需服务器获取页面)? 对于像XMLHttpRequest这样的方法,有什么限制可以阻止这种情况,有没有办法绕过它们或其他方法?
这是一个普遍的问题,特别是我想检查一系列随机网站并查看它们是否包含某个元素,因此我需要网站的HTML内容而不下载任何其他文件; 所有这些都在JavaScript文件中, 在服务器上没有任何转发或代理机制 。
(注意:一种方法是使用Greasemonkey及其GM_xmlhttpRequest。)
你应该看看jQuery 。 它具有丰富的AJAX功能 ,可以让您完成所有这些功能。 您可以加载外部页面,并使用直观的类似CSS的选择器解析它的HTML内容。
使用$.get();
的示例$.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
});
对于外部域,我必须编写一个本地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
});
给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"]);
?>
这很容易......如果你知道'秘密'技巧几乎没有人分享..
它叫做Yahoo yql ...
因此,为了重新获得“用户权力”(并回到方便的口头禅:'永远不接受'),只需使用http://query.yahooapis.com/ (而不是php?代理服务器端脚本)。
jQuery不是严格需要的。
例1:
使用类似SQL的命令:
select * from html
where url="http://stackoverflow.com"
and xpath='//div/h3/a'
以下链接将搜索SO以获取最新问题(绕过跨域安全公牛$!!7):
http://query.yahooapis.com/v1/public/yql?q=select%20title%20from%20html%20where%20url%3D%22http%3A%2F%2Fstackoverflow.com%22%20and%0A%20% 20%20%20%20%20xpath%3D%27%2F%2Fdiv%2Fh3%2FA%27%0A%20%20%20%20&格式= JSON&回调= cbfunc
如您所见,这将返回一个JSON数组(也可以选择xml)并调用callback-function: cbfunc
。
事实上,作为一个“奖励”,每当你不需要从'tag-soup'中取出正则数据时,你也会保存一只小猫 。
你是否听到自己内心开始傻笑的疯狂科学家?
然后查看此答案以获取更多信息(并且不要忘记它的注释以获取更多示例)。
祝好运!
编写一个代理脚本,该脚本沿着来自您域的http请求转发,这将绕过XMLHttpRequest限制。
如果你使用PHP,只需使用cURL来请求和阅读页面,然后简单地吐出html,好像它来自你的域。
更新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'); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
演示:
$.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'); } })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Allow-Control-Allow-Origin: *
铬
chrome.exe --args --disable-web-security
火狐
about:config -> security.fileuri.strict_origin_policy -> false
结束
noob old answer 2011
$获得(); 可以从jsbin.com获取数据,但我不知道为什么它无法从google.com等其他网站获取数据
$.get('http://jsbin.com/ufotu5', {},
function(results){ alert(results);
});
演示: http : //jsfiddle.net/Xj234/使用firefox,chrome和safari进行测试。
您还可以使用iframe模拟ajax请求。 这可以节省您为前端问题编写后端解决方案的麻烦。 这是一个例子:
function setUploadEvent(typeComponet){
var eventType = "";
var iframe = document.getElementById("iframeId");
try{
/* for Mozilla / Opera9 */
if (/(?!.*?compatible|.*?webkit)^mozilla|opera/i.test(navigator.userAgent)) {
eventType = "onload";
}else{
/* IE */
eventType = "onreadystatechange";
}
iframe[eventType] = function(){
var doc = iframe.contentDocument || iframe.contentWindow.document;
var response = doc.body.innerHTML; /* or what ever content you are looking for */
}
}
catch(e){
alert("Error loading content")}
}
这应该够了吧。 请注意,浏览器检测行并不是最干净的,你应该绝对使用所有最常见的JS框架(Prototype,JQuery等)中提供的那些。
非常感谢,这真是一个很好的伎俩。 我是这样做的:
的test.html
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","sp.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
sp.php
<?php
print file_get_contents("http://your.url.com/you-can-use-cross-domain");
?>
<script language =“JavaScript”type =“text / javascript”src =“http://www.example.com/hello.js”> </ script>
您可以将数据作为数组,JSON或类似内容添加到hello.js中。 示例:var daysInMonth = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
从另一台服务器获取JavaScript并不简单.. :-)
您需要在服务器上编写代理才能执行此操作。 所有请求都将发送到您的服务器,然后您的服务器将加载html并将其发送回客户端。 并且没有好方法只通过javascript实现这一点。
jQuery包含使用XmlHttpRequest加载JSON数据或外部脚本的功能,但此功能不能用于html页面。 您也可以查看jQuery邮件列表的这个主题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.