Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

php - Updating list of <select> options using jquery and ajax

I am trying to make an html select list of options update according to a selection made on a prior html select object. My jquery is below. This is being called correctly.

var brandName = $("#Brand").val();

$.get("updateTypes.php?q="+brandName, function(data) {

    $("#Type").remove();
    var typeData = JSON.parse(data);

    for (loop=0; loop < typeData.length; ++loop) {
        $("#Type").options.add(new Option(typeData[loop]));
    }
});

As I am using a singleton to interface with my mySQL database, this jquery function calls a 'go-between' .php file called updateTypes.php which is below:

include 'databaseInterface.php';
$brand = $_GET["q"];
$typesData = databaseInterface::getBrandTypes($brand);
return $typesData;

This calls the getBrandTypes function in my singleton below:

$query = "SELECT psTypeName FROM types WHERE brands_psBrandName='$BrandName'";
$result = mysqli_query($con, $query) or die ("Couldn't execute query. ".mysqli_error($con));
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) { 
    extract($row);
    $resultArray[] = $psTypeName;   
}

return json_encode($resultArray);

The webpage correctly removes the existing options from the jquery function but fails to update them. It seems to go wrong when I decode the JSON data in the jquery. Why is it going wrong? Is the loop for updating the select object appropriate?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use $.getJSON if your expecting a json response. You might also be able to use $.each() and then simply .append() to the select tag. You can reference this.property inside the .each().

Something like the following:

$.getJSON("updateTypes.php?q="+brandName, function(data) {
    $("#Type").html('');
    $.each(data, function(){
        $("#Type").append('<option value="'+ this.value +'">'+ this.name +'</option>')
    )
})

This would assume your json response is something like the following:

[ { name : "foo", value : "bar" }, { name : "another", value : "example" } ]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...