2013-07-05 39 views
0

我做了一個返回json數據的ajax調用,告訴我要加載什麼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); 
    } 
}); 

回答

1

使用完整的回調負荷的說法,使負載#ques_intro等過程中添加的元素是可訪問的,一旦加載完成。其他方面,它會運行負載和其他語句作爲負載異步。

$('#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

這完美地工作!非常感謝! – user1916500

+0

@ user1916500請記住標記爲答案.. :) – PSL

1

一個簡單的方法是指定一個回調處理器,讓你等到你的模板已經加載插入內容。

根據jQuery.load規範,您只需在加載參數後傳入回調處理程序。

例如..

$('#player-template').load(data.template_name,function(){ 
    $('#ques_intro').html(data.ques_intro); 
    $('#question').html(data.question); 
}); 
+0

謝謝,正是我在找的! – user1916500