我正在提取一些会有所不同的JSON数据......例如:
返回的数据可能是:
[{"userID":"2779","UserFullName":" Absolute Pro-Formance"},{"userID":"2780","UserFullName":" AR Fabrication"},{"userID":"2781","UserFullName":" Banda Lucas Design Group"}]
或:
[{"orderID":"112958","OrderName":"Order ID: 112958"},{"orderID":"112957","OrderName":"Order ID: 112957"},{"orderID":"112956","OrderName":"Order ID: 112956"}]
我尝试做的是处理此JSON以构建<select>
列表。
// Load in a drop-down as JSON
function LoadDropDown($url, $where, $id, $selectName){
var $loading = '<div class="pageLoader" style="margin:0 auto !important;padding:0 !important;"><img src="/assets/images/ajax-loader.gif" alt="loading..." height="11" width="16" /></div>';
var $t = Math.round(new Date().getTime() / 1000);
var $container = jQuery($where);
var options = {
url: $url + '?_=' + $t,
cache: false,
type: 'POST',
beforeSend: function(){
$container.html($loading);
},
success: function(data, status, jqXhr){
$html = '<select class="form-control" id="'+$selectName+'" name="'+$selectName+'">';
$html += '<option value="0">- Select an Option -</option>';
for(var i = 0; i < data.length-1; ++i) {
var item = data[i];
console.log(item.userID);
}
$html += '</select>';
$container.html('<pre>' + data + '</pre>');
},
complete: function(jqXhr, status){},
error: function(jqXhr, status, error){
$container.slideDown('fast').html('<div class="alert alert-danger alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button><i class="fa fa-exclamation-triangle fa-4x pull-left"></i><p><strong>Danger Will Robinson!</strong><br />There was an issue pulling in this page. Our support team has been notified, please check back later.</p></div>');
}
};
jQuery.ajax(options);
}
我遇到的问题是......#1 console.log(item.userID);
始终显示undefined
,而#2如何才能有效地动态构建选项?返回的JSON将始终包含每row
和id
两个项目以及name
for(var $key in data){
var $val = data[$key];
for($j in $val){
console.log('name:' + $j + ' = ' + $val[$j]);
}
}
向我显示我在Firefox控制台中需要的内容...但每行1个项目(例如第1个JSON)name:userID = 1234
下一行name:UserFullName = TheName
如何获取它们以便我可以构建我的<options>
?
使用:
for(var k in data) {
console.log(k, data[k]);
}
我回来了:
2955 Object { orderID="8508", OrderName="Order ID: 8508"}
和
2955 Object { userID="1355", UserFulleName="Me Myself And I"}
答案 0 :(得分:3)
您不需要使用这种凌乱的代码。同样在您的Ajax设置中dataType:"json"
success:function() {
var listB=$('#yourdropdownId');
listB.empty();
$.each(result, function (index, item) {
listB.append(
$('<option>', {
value: item.userID,
text: item.UserFullName
}, '<option/>'))
});
}
如果你只想从服务器
中检索json,那么$ .getJson而不是ajax$.getJSON('@Url.Action(" "," ")',
{ "youparametername": yourdata}, function (data) {
$.each(data, function (index, item) {
})
});
答案 1 :(得分:1)
在options对象中,请务必使用
dataType: 'json'
或者在成功处理程序中,您可以使用
JSON.parse(data)
答案 2 :(得分:0)
Cured:改变我的循环以循环返回JSON中的每个项目,得到他们的密钥等......
var $dl = data.length;
for(var $i = 0; $i < $dl - 1; ++$i) {
var $keys = Object.keys(data[$i]);
$html += '<option value="' + data[$i][$keys[0]] + '">' + data[$i][$keys[1]] + '</option>';
}