2013-05-01 95 views
1

我正在使用koExternalTemplateEngine加載外部模板。遠程服務器上的外部模板(通過http)

當模板位於同一站點或從同一服務器上的其他站點提供時,此工作正常。

但是,當我嘗試引用遠程服務器上的模板時,它不起作用。我得到http 200確定,但狀態碼爲0(響應中沒有任何內容並且沒有html)。

A碼例子如下:

<script src="Content/Scripts/ko/lib/koExternalTemplateEngine_all.js"></script> 
<script>infuser.defaults.templateSuffix = ".tmpl.html"; 
infuser.defaults.templateUrl = "http://www.anotherServer.com/koTemplates";</script> 
<div data-bind="template: { name: 'koTemplate1' }"></div> 

是否有可能引用一個遠程服務器上,如果是這樣我錯過什麼模板?

+0

這是'$ .ajax' /瀏覽器的限制,你不能把請求發送到從JavaScript不同的服務器:看http://stackoverflow.com/questions/1201429/jquery-ajax-fails- when-url-is-from-different-server – nemesv 2013-05-01 07:53:03

+0

啊,很酷,謝謝。 – 2013-05-01 08:39:23

回答

0

我建議你去使用requireJS的路線和加載外部交叉原屬含量最高的文字插件和配置XHR使用有:

config: { 
     text: { 
      useXhr: function (url, protocol, hostname, port) { 
       return true; 
      } 
     } 
    } 

你可以使用這個屬性在requirejs配置進行設置使用xhr並激活CORS。

確保在IE 6和IE 7和IE 8和9,這並不工作,你需要使用:

window.XDomainRequest 

一旦你做了這一切,你可以simlpy打電話給你的外部模板作爲requirejs模塊依賴像這樣:

define("moduleName", ["ko", "text!templates/surveys.html"], 
function(html){ 
    $('body').append(html); 
    ko.applyBindings(new viewmodel)... 
}); 

對你有一些很好的鏈接: require.js is requesting html files but serving them as script elements

https://github.com/requirejs/text

Configuring xdr for IE

+0

它看起來像我要在同一臺服務器上託管模板,現在解決了問題。不過,我會在未來記住這一點,謝謝。 – 2013-05-01 13:47:17