[英]show values of json data by jquery
I have my data returned by Json but somehow I'm not able to print it out. 我有Json返回的数据,但以某种方式无法打印出来。
here is my javascript
这是我的
javascript
jQuery( document ).ready( function( $ ) {
$('select[name="country_id"]').on('change', function() {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var CountryId = $(this).val();
if(CountryId) {
$.ajax({
url: '{{ url('profilegetStateList') }}/'+encodeURI(CountryId),
type: "GET",
dataType: "json",
success:function(data) {
console.log(data);
// $('select[name="state_id"]').empty();
// $('select[name="state_id"]').empty().append('<option value='+ data +' selected>'+data+'</option>');
}
});
}else{
$('select[name="state_id"]').empty().append("<option value='' selected>Select</option>");
}
});
});
I have tried data
, data->name
, data['name']
all of them return [object object]
我试过
data
, data->name
, data['name']
都返回[object object]
here is my console prints on console.log(data);
这是我在
console.log(data);
上的控制台打印内容console.log(data);
[]
length: 0
__proto__: Array []
[…]
0: Object { id: 1, name: "ACEH", country_id: 101 }
1: Object { id: 16, name: "BALI", country_id: 101 }
2: Object { id: 15, name: "BANTEN", country_id: 101 }
.....
length: 32
__proto__: Array []
any idea? 任何想法?
By seeing your code, I think the commented code should be like 通过查看您的代码,我认为注释后的代码应该像
var options = '';
data.forEach(function(country) {
options += '<option value='+ country.id +' selected>'+country.name+'</option>'
})
$('select[name="state_id"]').empty().append(options);
The data that you are consoling, is in array format. 您要合并的数据为数组格式。 You need to access each index of object.
您需要访问对象的每个索引。 Try this inside success function,
试试这个成功函数
for(var i=0;i<data.length;i++ ){
console.log('name-',i,'= ',data[i].name)
}
[object Object] is the default toString representation of an object in javascript. [object Object]是javascript中对象的默认toString表示形式。
If you want to know the properties of your object, just foreach over it like this: 如果您想知道对象的属性,只需像这样遍历它:
for(var property in data) {
alert(property + "=" + data[property]);
}
UPDATE 更新
for(var property in data) {
if(data[property]){
console.log(data[property])
}
}
Cant Comment.. so here is an addition to @Aswin Ramesh: Maybe remove the selected property from the options attributes and add it only to the first option. 不能评论。.因此,这里是@Aswin Ramesh的补充:也许从options属性中删除所选属性,并将其仅添加到第一个选项。 This was a mistake of the OP
这是OP的错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.