--Helper--
var uiHelper = function() {
var htmls = {};
var getHTML = function (options) {
/// <summary>Returns HTML in a string format</summary>
/// <param name="options" type="object">options{url:The url to the file with the HTML,successCallback:function,errorCallback:function,isAsync:true||false,cache:true|false}</param>
function xhrSuccess() {
if (this.cache) { htmls[this.url] = this.responseText; };
if (this.successCallback) {
this.successCallback.apply(this.responseText, this.arguments);
} else {
return htmls[this.url];
};
};
function xhrError() {
if (this.errorCallback) {
this.errorCallback.apply(this.statusText);
} else {
return this.statusText;
};
};
if (!htmls[options.url]) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", options.url, options.isAsync);
xmlhttp.cache = options.cache || false;
xmlhttp.url = options.url;
xmlhttp.onload = xhrSuccess;
xmlhttp.onerror = xhrError;
xmlhttp.successCallback = options.successCallback || undefined;
xmlhttp.errorCallback = options.errorCallback || undefined;
xmlhttp.send();
} else {
if (options.successCallback) {
options.successCallback.apply(htmls[options.url], this.arguments);
} else {
return htmls[options.url];
};
};
};
return {
getHTML: getHTML
};
}();
--usage ---
uiHelper.getHTML({
url: url, isAsync: true, cache: false, successCallback: function() {
document.getElementById('dynamicContent').innerHTML = this;
}
});
- 您的HTML ---
<div id="header">
<h2>Header here</h2>
</div>
<div id="dynamic-content">
<p id='dynamicContent'>-- Dynamic content here --</p>
</div>
<div id="footer">
<h3>Footer</h3>
</div>
要做到這一點以更「現代」的方式,您希望使用像Angular,Knockout或其他具有雙向數據的JS框架 捆綁。儘管如此,還是有一些輕微的學習曲線。我知道很多我使用jQuery在應用程序中輪詢/加載內容的情況。我不認爲有錯誤或正確的方法。 –
如果你打算傳遞一大串html,你最好使用客戶端模板解決方案(把手,小鬍子等) –
@GregJennings如果我從服務器獲取HTML標記,然後餵食Handlerbars或小鬍子的標記還好嗎? – Durty