如何使用 jQuery AJAX 加载跨域 html 页面? [英] How can I load cross domain html page with jQuery AJAX?

查看:46
本文介绍了如何使用 jQuery AJAX 加载跨域 html 页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jQuery AJAX 加载跨域 HTML 页面?

How can I load cross domain HTML page with jQuery AJAX?

假设我想使用 jQuery AJAX 在我的域之外获取一个页面:

Suppose I want to get a page outside my domain using jQuery AJAX:

$.get('http://www.domain.com/mypage.html', function(data) {
  alert(data);
});

我可能会收到此错误消息:

I will probably get this error message:

XMLHttpRequest 无法加载 http://www.domain.com/path/filename.起源Access-Control-Allow-Origin 不允许 null.

XMLHttpRequest cannot load http://www.domain.com/path/filename. Origin null is not allowed by Access-Control-Allow-Origin.

由于 同源策略,我们无法使用 AJAX 加载跨域页面.

we can't load cross domain page using AJAX because of the Same-origin policy.

我可以尝试使用 'jsonp' 来绕过这个限制:

I could try using 'jsonp' to bypass this restriction:

$.ajax({
  type:     "GET",
  url:      url,
  dataType: "jsonp",
  success: function(data){
    console.log(data);
  }
});

但是如果这个站点不支持jsonp"怎么办?这可能是个问题.

But what if 'jsonp' is not supported in this site? this could be a problem.

如果我只想读取外部页面并解析其 HTML 怎么办?

What if I just want to read an external page and parse its HTML?

推荐答案

我知道这是一个旧帖子.但是,我希望这会帮助其他正在寻找相同的人.

只是你不能. - 同源策略或者你需要为 www.domain.com

Simply you can't. - same-origin policy or you need to set CORS headers for www.domain.com

但是,如果您只想将外部页面内容提取到您的页面,您可以使用一种解决方法:

But, If you just want to fetch an external page content to your page, there is a workaround you could do:

在您的服务器中创建一个端点以返回给定外部 URL 的 HTML 内容.(因为您无法将外部内容获取到浏览器 - 同源策略)

Create an endpoint in your server to return the HTML content for the given external URL. (because you can't get external content to the browser - same-origin policy)

JS:

var encodedUrl = encodeURIComponent('http://www.domain.com/mypage.html');
$.get('http://www.yourdomain.com/getcontent?url=' + encodedUrl, function(data) {
    console.log(data);
});

在 .NET 中从 URL 读取到字符串的最简单方法 - 可以使用这个创建 /getcontent 端点

这篇关于如何使用 jQuery AJAX 加载跨域 html 页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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