我以json
字符串形式发送已排序的散列图数据,但在打印json
数据时,它不会以现有形式打印。
json
数据
{
"409": "A T (C T)",
"397": "A T (Government Model School)",
"407": "A T (Junior)",
"420": "A T (L T Adhoc Siksha Bandu)",
"406": "A T (L T)",
"408": "A T (Primary)",
"500": "AT(JBT)",
"402": "H M (High School)",
"403": "H M (Junior)",
"404": "H M (Primary)",
"405": "Lecturer",
"419": "Lecturer (Adhoc Siksha Bandu)",
"401": "Principal",
"398": "Siksha Acharya",
"399": "Siksha Mitra"
}
打印数据时
我的创建下拉列表代码是:
$.each(responseJson, function (key, value) {
$('#post_code').append(
$("<option></option>").text(value).val(key));
});
答案 0 :(得分:0)
下拉数据看起来像是按key
(397,398,399 ...)而不是value
排序。
JavaScript对象没有订单。即使大多数浏览器按照相同的顺序迭代创建属性,也有no guarantee
,因此对象不支持排序。
如果您需要可排序列表,则必须将其存储为对象数组:
var obj = [
{key:"409", val:"A T (C T)"},
{key:"397", val:"A T (Government Model School)"},
{key:"407", val:"A T (Junior)"},
{key:"420", val:"A T (L T Adhoc Siksha Bandu)"},
{key:"406", val:"A T (L T)"},
{key:"408", val:"A T (Primary)"},
{key:"500", val:"AT(JBT)"},
{key:"402", val:"H M (High School)"},
{key:"403", val:"H M (Junior)"},
{key:"404", val:"H M (Primary)"},
{key:"405", val:"Lecturer"},
{key:"419", val:"Lecturer (Adhoc Siksha Bandu)"},
{key:"401", val:"Principal"},
{key:"398", val:"Siksha Acharya"},
{key:"399", val:"Siksha Mitra"}
];
$(document).ready(function() {
$.each(obj,function(key,value)
{
var option = $('<option />').val(value.key).text(value.val);
$("#dropDownDest").append(option);
});
});
输出
答案 1 :(得分:0)
您的 responseJson 变量是一个对象。
“对象是一组无序的键/值对”
无法保证对象的排序。每次执行都可以选择不同的顺序最好将数据保存为数组。