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

匿名 (未验证) 提交于 2019-12-03 01:18:02

问题:

How can I load cross domain HTML page with 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 cannot load http://www.domain.com/path/filename. Origin null is not allowed by Access-Control-Allow-Origin.

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

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

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

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

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

回答1:

I know this is an old post. But, I hope this will help someone else who is looking for the same.

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:

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); }); 

Easiest way to read from a URL into a string in .NET - may use this to create /getcontent endpoint



回答2:

You can use 'AJAX Cross Origin' a jQuery plugin to load cross domain HTML page. AJAX Cross Origin is a jQuery plugin to allow Cross Origin AJAX requests. With this plugin we can easily bypass the Same-origin policy and do cross domain requests.

It is very simple to use:

   $.ajax({         crossOrigin: true,         url: url,         success: function(data) {             console.log(data);         }     }); 

You can read more about it here: http://www.ajax-cross-origin.com/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!