将动态数据加载到动态元素中

时间:2013-07-05 21:15:40

标签: jquery ajax

我做了一个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);
  } 
});

2 个答案:

答案 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);
});