使用AJAX加载外部html页面

时间:2016-10-16 16:36:23

标签: jquery ajax

我正在尝试使用ajax加载外部html页面,但我无法得到如下响应:

example.com

我的请求代码是:

$.ajax({
    type: "GET",
    url: "https://login.yahoo.com/",
    dataType: "json",
}).success( function( data ) {
    $( 'div.ajax-field' ).html( data );
});

我总是得到这个错误的原因?

  

MLHttpRequest无法加载https://login.yahoo.com/。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问“localhost:8000 / dashboard”。

1 个答案:

答案 0 :(得分:0)

跨站点请求的最佳解决方案是使用heroku api。

,因为您正在使用CORS

这是工作代码

 <div id="yahoo"></div>
  <script type="text/javascript">
$(document).ready(function(){
      var text = 'https://login.yahoo.com/';
      $.ajaxPrefilter( function (options) {
        if (options.crossDomain && jQuery.support.cors) {
          var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
          options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
          //options.url = "http://cors.corsproxy.io/url=" + options.url;
        }
      });

      $.get(
          'https://login.yahoo.com/',
          function (response) {

          var res = response;
           $('#yahoo').append(res);


      });

  });


</script>