php 使用 jquery 和 ajax 更新 <select> 选项列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17384705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:48:00  来源:igfitidea点击:

Updating list of <select> options using jquery and ajax

phpjqueryajaxjson

提问by Ben Thompson

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.

我正在尝试根据在先前的 html 选择对象上所做的选择来更新选项的 html 选择列表。我的jQuery在下面。这是正确调用。

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:

当我使用单例来连接我的 mySQL 数据库时,这个 jquery 函数调用了一个名为 updateTypes.php 的“中间”.php 文件,如下所示:

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

This calls the getBrandTypes function in my singleton below:

这将调用下面我的单例中的 getBrandTypes 函数:

$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?

该网页正确地从 jquery 函数中删除了现有选项,但无法更新它们。我在jquery中解码JSON数据时似乎出错了。为什么会出错?更新选择对象的循环是否合适?

回答by Shawn Northrop

You can use $.getJSONif your expecting a json response. You might also be able to use $.each()and then simply .append()to the selecttag. You can reference this.propertyinside the .each().

$.getJSON如果您期待 json 响应,您可以使用。您也许还可以使用$.each()然后简单.append()select标记。您可以this.property.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:

这将假设您的 json 响应类似于以下内容:

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

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

回答by Marcin Krawiec

Your code $("#Type").remove();removes the select object not its options. The correct way of removing options is:

您的代码$("#Type").remove();删除了选择对象而不是其选项。删除选项的正确方法是:

$("#Type option").remove();

or

或者

$("#Type").html('');

The second solution seems to be better as stated here: How to remove options from select element without memory leak?

第二种解决方案似乎更好,如下所述:How to remove options from select element without memory leak?

There is also an error in the part that adds new options. Your javascript code should be:

添加新选项的部分也有错误。你的 javascript 代码应该是:

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

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

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

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

The $('#Type').get(0)method refers to the raw DOM object which has the "options" property that you wanted to use (How to get a DOM Element from a JQuery Selector)

$('#Type').get(0)方法指的是原始 DOM 对象,该对象具有您想要使用的“选项”属性(如何从 JQuery 选择器获取 DOM 元素