0

我进行了一个 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);
  } 
});
4

2 回答 2

1

使用 load 的完整回调参数,以便在加载#ques_intro完成后可以访问在加载等期间添加的元素。否则它将运行 load 和其他语句,因为 load 是异步的。

 $('#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(网址,完成(responseText,textStatus,XMLHttpRequest))

于 2013-07-05T21:17:00.343 回答
1

一个简单的方法是指定一个回调处理程序,以便您等到您的模板加载后插入内容。

根据jQuery.load规范,您只需要在 load 参数之后传入一个回调处理程序。

例如..

$('#player-template').load(data.template_name,function(){
    $('#ques_intro').html(data.ques_intro);
    $('#question').html(data.question);
});
于 2013-07-05T21:18:32.163 回答