inlude指令加载页面失败的原因与解决方法

AngularJS中提供的ng-include指令,很类似于JSP中的<jsp:include>用来将多个子页面合并到同一个父页面中,避免父页面过大,可读性差,不好维护。

父页面parent.html代码如下:

<html> <head> <script src="https://www.jb51.net/angular-1.2.2/angular.js"></script> <script> function rootController($scope,$rootScope,$injector) { $rootScope.name = "aty"; $rootScope.age = 25; } </script> </head> <body ng-app ng-controller="rootController"> <h1>Hello, {{name}}!</h1> <h1>Hello, {{age}}!</h1> <div ng-include="'child.html'"> <input type="button" value="2"/> </div> </body> </html>

被包含的子页面child.html代码如下:

<div> <h1>included, {{name}}!</h1> <h1>included, {{age}}!</h1> </div>

我用IE11和Chrome39运行parent.html,发现child.html页面不能包含到parent.html中。IE下报错信息如下:

Error: 拒绝访问。
   at Anonymous function (file:///D:/learn/angular-1.2.2/angular.js:7852:7)
   at sendReq (file:///D:/learn/angular-1.2.2/angular.js:7720:9)
   at serverRequest (file:///D:/learn/angular-1.2.2/angular.js:7454:9)

chrome下报错信息如下:

XMLHttpRequest cannot load file:///D:/learn/include.html.
Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/learn/include.html'.

IE下的提示有些晦涩,不过chrome提示很明显:不能跨域访问。通过上面的错误提示,可以看到:使用ng-include指令的时候,会用到AJAX请求XMLHttpRequest。但是我们是直接用浏览器打开的parent.html,并没有通过web容器访问,所以存在跨域访问问题,加载child.html也就失败了。解决办法很简单:将代码部署到tomcat等web容器下,通过http访问即可。

平时在练习JavaScript或者是JS框架的时候,一版都是使用比较轻量级的工具,不会使用像Eclipse之类IDE,我一般使用Notepad++编写js代码。Notepad++可以方便地调用本机安装的浏览器。像ng-include这样的指令,必须要有web容器的支持。可以使用前端开发神器webstorm,该工具运行html的时候,会自动启动内置的web容器,这样ng-include指令就不会报错了。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwdzpd.html