我正在尝试升级网站以使用 jsRender 模板(它曾经使用 jTemplates)并且我一直在研究 jsRender(Boris 的网站和 John Papa 制作的材料)并尝试按照此处的说明进行操作:JSViewsRemoteLoadTemplates
请注意,截至 2013 年 11 月 13 日,此问题已被编辑以反映部分解决方案并清理内容:
经过大量实验后,我能够让 jsRender 模板处理静态数据,但是一旦我将数据更改为 ajax 源,模板就会呈现为空。我相信它可能会呈现为空,因为我没有在 .js 模板本身中指定正确的措辞,但我已经尝试了各种变体,但还没有任何效果。
我的页面是一个基本的.htm 页面。我在标题中使用 jQuery 1.10.2、json.js 和 jsrender.min.js。这是我在页面上的脚本:
<script style='text/javascript'>
$(function () {
lazyGetTemplate('PopupChildren');
});
function lazyGetTemplate(name) {
var deferred = $.Deferred();
if ($.templates[name]) {
deferred.resolve();
}
else {
$.getScript("/_Scripts/" + name + ".js").then(function () {
if ($.templates[name]) {
deferred.resolve();
}
else {
alert("Script: \"" + name + ".js\" failed to load.");
deferred.reject();
}
});
}
}
/* This is my sample static data that jsRender works with */
var staticdata = [
{
"TypeID": "88", "Value": "ORGANICS"
},
{
"TypeID": "89", "Value": "SPECIFIED ORGANICS"
}
];
function getMyTemplate(data) {
$div_Child.html($.templates.PopupChildren.render(data));
//change data to staticdata to test static info, I've also set this to JSON.stringify(data) but the result is still empty
}
/* This is the ajax that calls the external function I'm using for testing */
function selItem(cControl, treeID, treeTrans) {
var parentID = treeID;
if ($(cControl).parent().find('ul').length == 0) {
$.ajax({
type: "Post",
url: "Contractor_ws.asmx/web_getChildren",
async: true,
dataType: "text",
data: "{parentID:" + parentID + ", popupType:'" + $('#hid_popupType').val() + "'}",
contentType: "application/json",
success: function (data) {
if (data != null) { //menu item has children
$(cControl).after("<div id=\"div_Child\"></div>");
$div_Child = $(cControl).parent().find('#div_Child');
$div_Child.hide();
getMyTemplate(data);
$div_Child.show('slow');
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
}
</script>
PopupChildren 脚本(模板):
$.templates("PopupChildren", "<ul>{{for}}<li><a onclick='selItem(this,'{{:TypeID}}','{{:Value}}');'>{{:Value}}</a></li>{{/for}}</ul>");
示例 ajax 数据:
数据:"{"d":[{"__type":"BLS","TreeCode":"0130","TreeType":"OBJ","ParentID":88,"Children":[],"TypeID" :89,"值":"无机酸,未指定","反式":"无机酸,未指定","Active_Flag":false},{"__type":"BLS","TreeCode":"0131"," TreeType":"OBJ","ParentID":88,"Children":[],"TypeID":90,"Value":"CHLORINE-CONTAINING OXYACIDS","Trans":"CHLORINE-CONTAINING OXYACIDS","Active_Flag “:错误的}]}”