2012-08-12 63 views
3

是的我在同一主题上有3或4个不同的答案,但我努力将它们结合起来创造我所需要的。我使用序列化这Json.Net导致下面的对象我的结果: 如何使用JQuery从Json对象创建此选择列表?

"[ { "Id": 1, "OrderInList": 1 }, 
    { "Id": 2, "OrderInList": 2 }, 
    { "Id": 4, "OrderInList": 3 } 
]" 

我想期权价值文本是OrderInList值(我后来其他使用ID的东西)。

我目前得到下面的代码,但它创建了选项框。我可以看到它为什么这样做,但我不知道如何改变它以使其起作用。

$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, null, function (jsonResult) { 
     $('#orderInList').attr('enabled', 'true'); 
     $.each(jsonResult, function() { 
      $.each(this, function(index, item) { 
           $('#orderInList').append(
            $("<option></option>") 
             .text(index) 
             .val(index) 
           ); 

      }); 
     }); 

任何帮助,将不胜感激!

回答

8

我想你想是这样的:

var jsonResult = [{ 
    "Id": 1, 
    "OrderInList": 1}, 
{ 
    "Id": 2, 
    "OrderInList": 2}, 
{ 
    "Id": 4, 
    "OrderInList": 3} 
] 

$('#orderInList').attr('enabled', 'true'); 
$.each(jsonResult, function() { 
    $('#orderInList').append(
     $("<option></option>").text(this.Id).val(this.OrderInList); 
    ); 
});​ 

DEMO

的完整代码

$.getJSON("/Json/GetOrderSelectList?parentCategoryId=" + postData, function(jsonResult) { 
    $('#orderInList').attr('enabled', 'true'); 
    $.each(jsonResult, function() { 
     $('#orderInList').append(
      $("<option></option>").text(this.Id).val(this.OrderInList) 
     ); 
    }); 
});​ 
+0

优秀。为jsfiddle +1,看起来像这个类型的东西真的很方便的网站。感谢负载。 – Kiada 2012-08-12 09:52:03

+0

@CraigWhitley不客气 – thecodeparadox 2012-08-12 09:52:32

0

你并不需要额外的呼叫。每个嵌套在第一次调用.each。只需在第一个.each调用中传递项目和索引,然后创建您的元素。 试试这个:

var json = [ { "Id": 1, "OrderInList": 1 }, 
    { "Id": 2, "OrderInList": 2 }, 
    { "Id": 4, "OrderInList": 3 } 
]; 

function createSelect(options){ 
    $.each(options,function(index,item){ 
      $("#orderInList").append($("<option></option>").attr("value", item.OrderInList).text(item.OrderInList)); 

    }); 
} 

$(document).ready(function(){ 
createSelect(json); 
}); 

工作实例:http://jsfiddle.net/BzC9N/