Jquery json requested okey, but no results
My code queries for some json but there seems not to be a result. When debugging using firebug, I can see that the request is done and returns the expected json 开发者_运维问答 (bottom).
The problem is that the next line, (var option =...) is never reached, so I expect that I did some thing wrong?
$.getJSON("Gateway.php?action=UserAction&subAction=json", function(result) {
var options = $("#creatorUserId");
$.each(result, function(item) {
options.append($("<option />").val(item.id).text(item.value));
});
});
The json:
json[{"id":"1","value":"Teddy"},{"id":"2","value":"Fred"},{"id":"3","value":"Roel"}]
The callback for $.each()
takes (up to) two parameters -- the first is an index number, and the second is a value. Your item
is always an index number, not the item object.
Try this:
Gateway.php?action=UserAction&subAction=json
should return:
[{"id":"1","value":"Teddy"},{"id":"2","value":"Fred"},{"id":"3","value":"Roel"}]
javscript/jquery:
$.getJSON( "Gateway.php?action=UserAction&subAction=json", function(result) {
var options = $("#creatorUserId");
$.each(result, function(num,item) {
options.append($("<option />").val(item.id).text(item.value));
});
});
Or, to use slightly less jQuery:
$.getJSON( "Gateway.php?action=UserAction&subAction=json", function(result) {
var options = $("#creatorUserId");
while(result) {
var item = result.shift();
options.append($("<option />").val(item.id).text(item.value));
};
});
精彩评论