欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

(十) ng-inlude指令加载页面失败的原因和解决方法_html/css_WEB-ITnose

程序员文章站 2022-06-12 21:50:29
...
angularjs中提供的ng-include指令,很类似于JSP中的用来将多个子页面合并到同一个父页面中,避免父页面过大,可读性差,不好维护。

父页面parent.html代码如下:

  

Hello, {{name}}!

Hello, {{age}}!

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

 

included, {{name}}!

included, {{age}}!


我用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指令就不会报错了。