Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

jquery - Dropdown populate ajax

I have the following issue: When i select an element from a drop down i want to auto populate another drop down via ajax. the idea is that the subcategory(sub_type) doesn't load after selecting the "type".

HTML
<select id="type" name="type">
<option value="1">General</option>
<option value="2">Test</option>
</select>
<select id="sub_type" name="sub_type">
</select>


SCRIPT
    $("#type").change(function(){
    $.getJSON("ajax/add_subcathegory.php",{id: $(this).val(), ajax: 'true'}, function(j){
          var options = '';
          for (var i = 0; i < j.length; i++) {
            options += '<option value="' + j[i].id+ '">' + j[i].name+ '</option>';
          }
        });
    $("#sub_type").html(options);
    });

My ajax script returns:

[{id: 0, name: 'Mark'}, {id:1, name: 'Andy'}, {id:2, name: 'Richard'}]

But the subcathegory (secont select) isn`t loaded.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assuming that the Ajax success function is indeed called, change the function code to:

          var $subType = $("#sub_type");
          $subType.empty();
          $.each(j, function () {
            $subType.append($('<option></option>').attr("value", this.id).text(this.name));
          });

Your main problems currently are:

  • the html function is called only once because it's outside of the sucess function.
  • the elements in the Ajax data have the keys id and name and not optionValue and optionDisplay

Update:

The returned JSON is invalid. String have to be quoted with double quotes, not single quotes. As a result, the getJSON() call fails silently.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...