我的问题类似于this question,除了我正在寻找基于AngularJS的解决方案来解决这个问题。
我的JSP页面中有一个iframe
,此iframe的src
是另一个域中的一个页面我想显示来自images
的图片如果iframe
无法加载src
页面,请填写文件夹。
我找不到可靠的方法来检查(或在响应到达时得到通知)关于跨域页面的可用性。请帮忙..
答案 0 :(得分:1)
在研究了更多关于这个问题之后,我开始知道这个问题是因为我的请求是跨域的,并且由于安全性,浏览器不允许这样的请求。因为如果允许互联网安全将是疯狂的处理。我找到了a very good帖子,详细解释了所有内容。
我尝试使用JQuery,JavaScript甚至JSONP请求都没有工作,因为我无法访问其他服务器。所以我在我的代码中使用了Server Side调用的解决方案。简而言之,我做了以下事情
在 processRequest 方法内添加了对第二方服务器(第三方)的调用。
protected void processRequest(HttpServletRequest request, HttpServletResponse httpServletResponse)
throws ServletException, IOException {
httpServletResponse.setContentType("image/png");
String url = "http://www.w3schools.com/angular/pic_angular.jpg";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedInputStream in = new BufferedInputStream(con.getInputStream());
byte[] imageArray = new byte[1024];
StringBuilder response = new StringBuilder();
BufferedOutputStream bout = new BufferedOutputStream(httpServletResponse.getOutputStream());
while ((in.read(imageArray)) != -1) {
bout.write(imageArray);
}
System.out.println(response.toString());
in.close();
bout.close();
}
我的Angular现在调用自己的服务器,而不是直接调用第三方服务器,请参阅下面的JS代码
var iFrameDemo = angular.module("iFrameDemo", []);
iFrameDemo.controller("iFrameDemoController", function ($scope, $sce, $http) {
url = "/webApp/controller";
$scope.iframesrcurl = url;
console.log('iframesrcurl is ' + $scope.iframesrcurl);
// url = 'http://www.w3schools.com/angular/pic_angular.jpg?&callback=JSON_CALLBACK';
$scope.desiredFrameSource = url;
$scope.errorImageSrc = '/webApp/images/thumb_down-512.png';
var responsePromise = $http.get(url);//'http://localhost:8084/iframe/newLogin.html');
responsePromise.success(function (data) {
console.log("AJAX call was success " + data.found);
$scope.iframesrcurl = $sce.trustAsResourceUrl(url);
});
responsePromise.error(function () {
console.log("AJAX call failed");
$scope.iframesrcurl = $scope.errorImageSrc;
});});
将JSP文件中的iframe声明为
<iframe ng-src="{{iframesrcurl}}" frameborder="0" width="100%" height="1100px" scrolling="auto" onload="iframeContentLoaded();" onerror="onerrorLoadingiFrame();">
<h3>No such page</h3>
</iframe>
就是这样..它的作用就像一个魅力而不是..如果你有更好的选择,请随时发布。希望这种方法对某人有帮助..