AngularJS使用ng-inlude指令加载页面失败的原因与解决方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

AngularJS使用ng-inlude指令加载页面失败的原因与解决方法

aitangyong   2020-05-15 我要评论

本文实例讲述了AngularJS使用ng-inlude指令加载页面失败的原因与解决方法。分享给大家供大家参考,具体如下:

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

父页面parent.html代码如下:

<html>
 <head>
  <script src="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 id="included" 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指令就不会报错了。

希望本文所述对大家AngularJS程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们