Problem In Looping JSON
I want to append data to selectbox. But, I got this error...
"Error: $("").attr("value", guruMapelId).html is not a function
Source File: http://localhost:8084/controller?aksi=kurikulum Line: 5"
this is my js code:
function dataGuruMapelSelect(dataSelect){
$.getJSON("controller", "aksi=dataGuruMapel", function(json){
$.each(json.guruMapelData, function(k,v){
var guruMapelId = v.guruMapelId;
var guruNama = v.guruNama ;
$('<option />').attr('value',guruMapelId).html(guruNama).appendTo(dataSelect);
})
});
}
And this is the JSON data
{
"guruMapelData": [
{
"guruMapelId ": "1",
"guruNip ": "1331/001",
"guruNama ": "HARI BUDIYONO DRS.",
"mapelNama ": "PPKn",
"tahunAjarNama ": "2010/2011",
"mapelKategoriNama ": "Normatif",
"mapelId ": "1"
},
{
"开发者_运维问答guruMapelId ": "2",
"guruNip ": "1331/002",
"guruNama ": "PENI WARDAYANI DRA",
"mapelNama ": "Kewirausahaan",
"tahunAjarNama ": "2010/2011",
"mapelKategoriNama ": "Produktif",
"mapelId ": "2"
}
]
}
What is my fault? Thanks before...
Your JSON keys contain spaces after their names, so the key is "guruMapelId "
, not "guruMapelId"
. You can either remove the space from your JSON keys or use var guruMapelId = v["guruMapelId "];
and var guruNama = v["guruNama "];
instead.
This was a tricky one. If you pass undefined
to attr
(attr('value', undefined)
) or html
(html(undefined)
), it will actually be the same as calling attr('value')
or html()
, which both return a string and not a jQuery object.
But wait, you say, I'm not passing undefined
, I'm passing the values of guruMapelId
and guruNama
!
Let's have a closer look: The keys in the JSON all have a trailing space. That means, v.guruMapelId
does not exist (hence is undefined
). You would have to access the data with
v['guruMapelId '] // <-- note the trailing space
Same for guruNama
. But better would be to create proper JSON.
DEMO
Check what you get in your $.getJSON (just use alert(guruMapelId) and guruNama ) call then you can just make your option as follow:
$('<option />').val(guruMapelId).text(guruNama)appendTo(dataSelect);
精彩评论