angularjs $http 文档加载到 iFrame 中

问题描述 投票:0回答:1

我已经阅读了两打参考文献,试图让 $http.get 从我的服务器中提取文档并将其加载到 iFrame 中。对文档的调用有效,并且全部存储在

data
中 - 我可以在 Chrome 的 Devtools 网络部分的
Preview
选项卡中看到渲染的 HTML。页面 data/html 在那里,但我无法让它在 iFrame 中渲染。

应用程序配置:

.config(function($sceDelegateProvider) {
  $sceDelegateProvider.resourceUrlWhitelist([
    'self',
    'https://api.example.com/v1/**'
  ]) ;
})

在服务中:

.factory("eventService",function($http) {

  var headers = {
    'Pragma' : 'no-cache', 
    'Expires' : -1, 
    'Cache-Control' : 'no-cache,must-revalidate', 
    'Content-Type' : 'application/json',        
    'X-Requested-With' : 'com.example',
    Authorization : 'Token ' +clientToken[0]
  } ;

  function eventShow(dataObj) {
    //dataObj[0].fullVer = appVersion.replaceAll(".","") ;   
    var baseUrl = "https://api.example.com/v1/events/eventsPage.html?e="+dataObj.e ;
    
    var req = {
      method: 'GET',
      url: baseUrl,
      timeout:30,
      headers: headers
    }

    return $http(req)
    .then(function(response){
      if (response.status == 200) {
        return {"success":true,data:response.data} ;
      } else {
        // received an improper response
        return {"success":false,error:response.status} ;
      }
    }
   });
  }

  return {
    eventShow(eventID) {
      console.log("tBuy: "+eventID) ;
      var dataObj = [{"e":eventID}] ;
      return eventShow(dataObj) ;
  }
})

在控制器中:

  eventService.eventShow($scope.club.ceID)
  .then(function(res) {
    if (res.success == true) {
      console.log(res.data) ;
      $scope.eventItem.url = $sce.trustAsHtml(res.data);
      //$scope.eventItem.url = "data:text/html;charset=utf-8," + escape(res.data);
      $scope.eventItem.isLogin = 1 ;        
    }
  }) ; 

模板 HTML:

  <iframe id="eventIframe" ng-src="{{eventItem.url}}" style="width:100%;height:100%;"</iframe>

在控制器中,

console.log
打印整个请求的页面 - 所以我知道它已加载到这一点,但我无法让它在 iframe 中显示/渲染。

在控制器中,使用

 $scope.eventItem.url = $sce.trustAsHtml(res.data);
时 - 没有任何内容加载到 iFrame 中,也不会产生错误,但在幕后,我看到整个应用程序重新加载了每个 JS 文件(应用程序 JS 和插件 JS)以及所有模板再次加载,应用程序功能崩溃。

当我更改控制器以使用

$scope.eventItem.url = "data:text/html;charset=utf-8," + escape(res.data);
- 我收到此错误:
Blocked loading resource from url not allowed by $sceDelegate policy
- 但我传递到 $http 调用的 URL 列在我的 $sceDelegate

javascript angularjs iframe http-get
1个回答
0
投票

我花了一段时间才发现,除了我如何将 HTML 文档附加到 iFrame 之外,一切都是正确的:

我将 iframe 更改为:

  <iframe id="eventIframe" ng-src="{{eventItem.url}}" style="width:100%;height:100%;"</iframe>

致:

  <iframe id="eventIframe" ng-attr-srcdoc="{{eventItem.url}}" style="width:100%;height:100%;"</iframe>

一切都很完美

© www.soinside.com 2019 - 2024. All rights reserved.