开发者

Loading values into an HTML select using jQuery/Json

I am trying to load values into a select dynamically using values from a json string.

The data is being loaded correctly, but for some reason, only the 1st value is loading into the select. Can anyone spot why this could be?

Here is my JSON data:

[{
  "cat_id": "1",
  "cat_section": "pages",
  "cat_type": "cat",
  "cat_name": "Music",
  "cat_order": "1",
  "cat_parent_id": "0"
}, {
  "cat_id开发者_Python百科": "2",
  "cat_section": "pages",
  "cat_type": "cat",
  "cat_name": "Arts & Culture",
  "cat_order": "2",
  "cat_parent_id": "0"
}, {
  "cat_id": "3",
  "cat_section": "pages",
  "cat_type": "cat",
  "cat_name": "Travel & Escape",
  "cat_order": "3",
  "cat_parent_id": "0"
}, {
  "cat_id": "4",
  "cat_section": "pages",
  "cat_type": "cat",
  "cat_name": "Technology",
  "cat_order": "4",
  "cat_parent_id": "0"
}]

An here is my jQuery:

$("select#select_category").change(function() {
  $.getJSON("<?php echo site_url()?>ajax/categories/pages/" + $(this).val(), function(data) {
    var options = '';
    for (var i = 0; i < data.length; data++) {
      options += '<option value="' + data[i].cat_id + '">' + data[i].cat_name + '</option>';
    }
    $("select#select_subcategory").html(options);
  })
});


it should be i++ not data++ in your for loop


for (var i = 0; i < data.length; data++) {

Should clearly be i++.

But in general you shouldn't create dynamic page content using HTML string-slinging. Your code will fail when category names contain characters that are special in HTML markup. If categories may be input by the user, that gives you cross-site-scripting security holes. Instead you can use the jQuery 1.4 creation shortcut $('<option>', {text: foo, value: bar}), or even more simply in this case, new Option(). Either way sets properties directly instead of embedded in a string, so you don't have to worry about HTML-escaping issues.

Also when you spit strings (or other data) from PHP to JavaScript source, you should be using json_encode() to convert them properly, otherwise you'll have problems with characters that are special in JavaScript string literals (', ", \ and various control codes) or the enclosing HTML file (</script>). Again, maybe this won't matter for the specific values you have here, but in general this stuff is the source of many security-sensitive escaping problems.

var siteurl= <?php echo json_encode(site_url(), JSON_HEX_TAG); ?>;

$('#select_category').change(function(){
    $.getJSON(siteurl+'ajax/categories/pages/'+$(this).val(), function(data) {
        $('#select_subcategory').empty();
        $.each(data, function() {
            $('#select_subcategory').append(new Option(this.cat_name, this.cat_id));
        });
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜