我做了一个ajax调用,返回json数据并告诉我要加载的html模板以及填充模板所需的数据。如果我在ajax调用之外加载模板,数据填充正常,但是如果我尝试在ajax调用中加载html,我看到html元素已经加载,但我无法填充它们。
$.ajax({
type: "POST",
url: "http://some-url/items-json/item_data.json",
dataType: "json",
async: true,
success: function( data ) {
// template_name will be an html file like template_10.html
// #player-template is the div id i want to load it into
$('#player-template').load(data.template_name);
// these elements get created from the dynamic template that gets loaded above
$('#ques_intro').html(data.ques_intro);
$('#question').html(data.question);
}
});
答案 0 :(得分:1)
使用load的完整回调参数,以便在加载完成后可以访问在加载#ques_intro
等期间添加的元素。另外,它会运行load和其他语句,因为load是async。
$('#player-template').load(data.template_name, function(){ // <-- Call back executes after the load is complete.
$('#ques_intro').html(data.ques_intro); //Now you can access the elements as they will be available in DOM
$('#question').html(data.question);
});
<强> .load( url , complete(responseText, textStatus, XMLHttpRequest) ) 强>
答案 1 :(得分:1)
一种简单的方法是指定一个回调处理程序,以便等到加载模板后插入内容。
根据jQuery.load规范,你只需要在load参数之后传入一个回调处理程序。
例如......
$('#player-template').load(data.template_name,function(){
$('#ques_intro').html(data.ques_intro);
$('#question').html(data.question);
});