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

How can I load cross domain html page with jQuery AJAX?(如何使用 jQuery AJAX 加载跨域 html 页面?)
本文介绍了如何使用 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 页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href
Rails 3.1 ajax:success handling(Rails 3.1 ajax:成功处理)
ExecJS::ProgramError: SyntaxError: Reserved word quot;functionquot;(ExecJS::ProgramError: SyntaxError: 保留字“function)
Infinite scroll and will_paginate appending the #39;next page#39; of items multiple times(无限滚动和 will_paginate 多次附加项目的“下一页)
Ajax call in rails 3.2.3 with will_paginate gem(使用 will_paginate gem 在 Rails 3.2.3 中调用 Ajax)