溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

AngularJS使用ng-inlude指令加載頁面失敗的原因與解決方法

發(fā)布時間:2020-09-24 02:47:10 來源:腳本之家 閱讀:166 作者:aitangyong 欄目:web開發(fā)

本文實例講述了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">
    <h2>Hello, {{name}}!</h2>
    <h2>Hello, {{age}}!</h2>
  <div id="included" ng-include="'child.html'">
      <input type="button" value="2"/>
    </div>
 </body>
</html>

被包含的子頁面child.html代碼如下:

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

我用IE11和Chrome39運行parent.html,發(fā)現(xiàn)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訪問即可。

平時在練習(xí)JavaScript或者是JS框架的時候,一版都是使用比較輕量級的工具,不會使用像Eclipse之類IDE,我一般使用Notepad++編寫js代碼。Notepad++可以方便地調(diào)用本機安裝的瀏覽器。像ng-include這樣的指令,必須要有web容器的支持??梢允褂们岸碎_發(fā)神器webstorm,該工具運行html的時候,會自動啟動內(nèi)置的web容器,這樣ng-include指令就不會報錯了。

更多關(guān)于AngularJS相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《AngularJS入門與進(jìn)階教程》及《AngularJS MVC架構(gòu)總結(jié)》

希望本文所述對大家AngularJS程序設(shè)計有所幫助。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI