js:从其他域加载页面的html [英] js: Load html of a page from a different domain

查看:520
本文介绍了js:从其他域加载页面的html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何载入在不同网域托管的HTML?

I was wondering how can I load HTML, which is hosted on a different domain?

我使用JavaScript,想要创建一个bookmarklet,

I am using JavaScript, and want to create a bookmarklet that will enable me to parse the external HTML.

我已经偷偷走了几个小时...

I have been googling for hours in vain...

推荐答案

JavaScript不允许发出跨网域请求。这是一个很大的安全风险。相反,您必须在服务器上执行一个脚本,并将结果返回给您的JavaScript函数。

JavaScript isn't allowed to make cross-domain requests. It's a big security risk. Instead, you'll have to execute a script on the server and have it return the results to your JavaScript function.

例如,假设您使用JavaScript和PHP可以将应用程序设置为这样工作:

For example, assuming that you're using JavaScript and PHP you could setup the application to work like this:

JavaScript向位于服务器上的页面(或脚本)发起Ajax请求。它将任何必需的参数传递到此页面。下面的代码是基于jQuery(为了简洁),但原则是一样的,不管你的框架。

JavaScript initiates an Ajax request to a page (or script) located on your server. It passes any required parameters to this page. The following code is based on jQuery (for the sake of being concise), but the principles are the same regardless of your framework.

var sParameters = " ... " // this is defined by you
$.ajax({
  url: 'your-server-side-code.php',
  processData: false,
  data: sParameters,
  success: function(sResponse) {
    // handle the response data however you want
  }
});

服务器端代码将响应请求并将必要参数传递到跨域网站。 PHP的 cURL库对此有帮助。

The server-side code will respond to the request and pass along the necessary parameters to the cross-domain website. PHP's cURL library is good for this.

// very contrivuted cURL configuration for purposes of example...
$curl_connection = curl_init();
$str_url = "http://you-url.com";
curl_setopt($curl_connection, CURLOPT_URL, $str_url);
curl_setopt($curl_connection, CURLOPT_GET, 1);
// ... keep setting your options ...
$str_response = curl_exec($curl_connection);
curl_close($curl_connection);

跨域网站响应时,服务器端代码可以将响应回应到初始请求。这应该可以在回应之前验证,但它只是一个例子。

When the cross-domain website responds, your server-side code can echo the response back to the initial request. This should probably be validated before responding back, but it's just an example.

print_r($str_response);

然后,JavaScript响应处理函数可以解析传入的响应数据。请注意上面第一个JavaScript代码块中的成功函数。

A JavaScript response handler function can then parse the incoming response data. Note the success function in the first block of JavaScript code above.

这篇关于js:从其他域加载页面的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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