如何从另一台服务器获取JavaScript数据? [英] How to get data with JavaScript from another server?

查看:431
本文介绍了如何从另一台服务器获取JavaScript数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在用户的浏览器中使用JavaScript向其他服务器发出请求(即从任何所需服务器获取页面)?对于像XMLHttpRequest这样的方法有什么限制可以阻止它,有没有办法绕过它们或其他方法?

How can I make requests to other server(s) (i.e. get a page from any desired server) with a JavaScript within the user's browser? There are limitations in place to prevent this for methods like XMLHttpRequest, are there ways to bypass them or other methods?

这是一个普遍的问题,特别是我想检查一个一系列随机网站,看看它们是否包含某个元素,所以我需要网站的HTML内容而不下载任何其他文件;所有这些都在JavaScript文件中,在服务器上没有任何转发或代理机制

That is a general question, specifically I want to check a series of random websites and see if they contain a certain element, so I need the HTML content of a website without downloading any additional files; all that in a JavaScript file, without any forwarding or proxy mechanism on a server.

(注意:一种方法是使用Greasemonkey及其GM_xmlhttpRequest 。)

(Note: one way is using Greasemonkey and its GM_xmlhttpRequest.)

推荐答案

你应该看看 jQuery的。它拥有丰富的 AJAX功能,可让您充分发挥所有这些功能。您可以加载外部页面,并使用直观的类似CSS的选择器解析它的HTML内容。

You should check out jQuery. It has a rich base of AJAX functionality that can give you the power to do all of this. You can load in an external page, and parse it's HTML content with intuitive CSS-like selectors.

使用$ .get();

An example using $.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脚本读取数据。

For external domains I've had to author a local PHP script that will act as a middle-man. jQuery will call the local PHP script passing in another server's URL as an argument, the local PHP script will gather the data, and jQuery will read the data from the local PHP script.

$.get("middleman.php", {"site":"http://www.google.com"}, function(results){
  alert(results); // middleman gives Google's HTML to jQuery
});

给midman.php一些东西

Giving middleman.php something along the lines of

<?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"]);

?>

这篇关于如何从另一台服务器获取JavaScript数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆