2014-11-02 57 views
0

我想根據我從PHP腳本獲得的列名,通過AJAX和預定義的列詳細數組來創建表單。我希望將這些預定義的屬性分配給傳入的列並構建表單。例如,如果我得到列 「用戶名」 我想永遠是一個<輸入>從數組中分配屬性

模板

var template = { 
    UserName : { 
       label: "User Name:", 
       type: "input" 
    } 
    UserId : { 
       label: "User Id:", 
       type: "text" 
    } 
} 

從AJAX請求傳入JSON陣列

{"UserName":"bob", "UserId":"1"} 

現在我需要以某種方式'匹配'這些。我自己並不確定在這裏做什麼。

$.each(data, function(i,e){ 
    // if index (such as UserName) is found in template array, maybe add the attributes to it? 
}); 

回答

1

對於你的情況,使用obj.hasOwnProperty(key)來測試它是否存在,將字符串和使用三元賦值來創建一個input元素。如果您願意,您也可以使用if語句。

var $html = ''; 
$.each(data, function(idx,v){ 
    $html += template.hasOwnProperty(idx)? '<input type="'+template[idx]['type']+'" name="'+idx+'"/>': ''; 
}); 
console.log($html); 

Here's your jsFiddle

+0

如果我JSON看起來更像[{「用戶名」:「鮑勃」,「用戶ID」:「1」}]我想有必要使用兩個$ .each語句到達元素「UserName」? – user3822370 2014-11-02 21:38:56

+0

@ user3822370不。這是一組對象。你應該有多個對象存儲在數組中,而不是每個對象的數組。這會讓代碼變得亂七八糟。用你現有的例子,使用:'.each(data [0],function(idx,v){' – Ohgodwhy 2014-11-02 21:39:52

+0

是的不幸的是,當我從PHP發送我的JSON數據時,我必須打破assoc數組並重新構建它可以對BLOB進行編碼)所以它最終會回來嵌套像這樣.. [{},{} ...] – user3822370 2014-11-02 21:43:13

1

的替代(和或許wordier)解決方案,包括標籤的處理可能會在此jsFiddle顯示。高水平是基於以下代碼:

$(function() { 
    var template = { 
     UserName: { 
      label: "User Name:", 
      type: "input" 
     }, 
     UserId: { 
      label: "User Id:", 
      type: "text" 
     } 
    }; 
    var data = { 
     "UserName": "bob", 
     "UserId": "1" 
    }; 
    $.each(data, function (key, value) { 
     if (template[key] != undefined) { 
      $("#here").append($("<span>" + template[key].label + "</span>")); 
      $("#here").append($("<input type=\"" + template[key].type + "\">")); 
      $("#here").append($("<br>")); 
     } 
    }); 
});