【问题标题】:Get HTML Content from another website like (http://www.google.com) using jquery使用 jquery 从另一个网站(如(http://www.google.com))获取 HTML 内容
【发布时间】:2014-03-26 15:24:32
【问题描述】:

我正在对 URL http://google.com 进行 Get 调用以获取网站的 html 内容,但在 ajax 调用中我最终出现以下 2 个错误,

错误:GET http://www.google.com/未定义(未定义)

错误:XMLHttpRequest 无法加载 google.com。 Access-Control-Allow-Origin 不允许“我的本地网站的 URL”。

第一个错误的代码:

$.ajax({
    type : "GET",
    cache : false,
    url : url,
    dataType : "xml",
    crossDomain : true,
    contentType : "text/html",
    success : function(data){
        alert("success");
    },
    error : function(error){
        alert("error");
    }
});

第二个错误的代码:

$.ajax({
    url : url,
    dataType : "text",
    success : function(data){
        alert("success");
    },
    error : function(error){
        alert("error");
    }
});

我需要做哪些设置才能启用跨域调用,非常感谢帮助。

我也尝试过设置 $.mobile.allowCrossDomainPages = true 和 $.support.cros = true;在 ajax 之前,即使这样也没有用。 非常感谢您的解决方案。

【问题讨论】:

  • 您可以使用第三方应用程序(使用服务器获取请求)来做到这一点。
  • 请参阅this question 以获得相关答案。您可能需要在您的服务器上有一个可以调用的 URL,该 URL 将返回 Google 的 HTML。

标签: jquery


【解决方案1】:

很久以前我创建了一个项目来解决这个问题。它是开源的on GitHub

  $.ajax({
    url: 'http://google.com', // Or your web page link
    type: 'GET',
    success: function(res) {
      var headline = res.responseText;
      htmlCodeTextArea.value = headline;
    }
  });

要下载它,请使用:

git clone git@github.com:IonicaBizau/jQuery-cross-domain-requests.git

或点击here

然后打开index3.html文件。

【讨论】:

  • @KyleK 它仍然对我有用。对于问题/错误报告,请打开issues here
【解决方案2】:

您正在执行一个跨域请求,作为一项安全措施,大多数浏览器都会阻止该请求。您只能在脚本运行时从同一域请求内容,或者需要服务器识别您的域并通过 Access-Control-Allow-Origin 标头允许跨域请求。

在此查看更多信息:http://en.wikipedia.org/wiki/Same_origin_policy

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2015-05-02
    • 2013-06-09
    • 2018-10-16
    相关资源
    最近更新 更多