简体   繁体   English

使用PHP级联JSON和JSON的jQuery下拉列表

[英]Cascading jQuery Dropdowns with JSON and Multiple MySQL Tables using PHP

I'm fairly new to PHP and MySQL, have a little experience with jQuery and almost no experience with JSON, just to give you some background. 我刚接触PHP和MySQL,对jQuery有一点经验,而对JSON几乎没有经验,只是为了给您一些背景知识。 I am trying to implement cascading dropdowns in my form. 我正在尝试在表单中实现级联下拉菜单。

I have two tables: 我有两个表:

|city|
|city_id INT| - PK
|city VARCHAR (45)|
|state_state_id INT | - FK

|state|
|state_id INT| - PK
|state VARCHAR (25)|

Here's my form: 这是我的表格:

State:<br />
<select name="state" id="stateName">
<?php foreach($rows as $row): ?>
<option value="<?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>"><?php echo htmlentities($row['state'],ENT_QUOTES,'UTF-8');?>
</option>
<?php endforeach; ?>
</select>
<br /><br />
City:<br />
<select name="city" id="cityName"></select>
<input type="submit" name="work_order_submit" id="" value="Add Work Order" />

I populate the State dropdown with this query: 我使用以下查询填充“状态”下拉列表:

$query = "SELECT * FROM state WHERE 1 ORDER BY state";
try{
$stmt = $db->prepare($query);
$stmt->execute();
}catch(PDOException $ex){
//On production remove getMessage.
die("Failed to run query: " . $ex->getMessage());
}

$rows = $stmt->fetchAll();

Here's the jQuery I've created to run the JSON and populate the City dropdown with the cascaded values from the state dropdown when a state is selected: 这是我创建的用于运行JSON并在选择状态时使用状态下拉列表中的级联值填充City下拉列表的jQuery:

<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName:$('#stateName').val()},
    function(data){
            var select = $('#cityName');
            var options = select.prop('options');
            $('option', select).remove();

            $.each(data, function(index, array){
                     options[options.length] = new Option(array['city']);
                     });

          });
}

$(document).ready(function(){
  populateCityName();
  $('#stateName').on('change', function(){
        populateCityName();
  });
});
</script>

And here's the code in the state-names.php file (I connect to the database before this code): 这是state-names.php文件中的代码(我在此代码之前连接到数据库):

$rows = array();
if(isset($_GET['stateName'])){
$query = "SELECT city FROM city INNER JOIN state ON city.state_state_id = state.state_id WHERE state = :state ORDER BY city";
$query_params = array(":state" => $_GET['stateName']);
try{
    $stmt = $pdo->prepare($query);
    $stmt->execute($query_params);
}catch(PDOException $ex){
    //On production remove .getMessage.
    die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
echo json_encode($rows);

Nothing happens when I select the state in the form. 当我在表单中选择状态时,什么也没有发生。 I don't even get an error. 我什至没有出错。 I've tested the SQL and it runs fine and retrieves the values that I want, but for some reason that I can't figure out, the values aren't being cascaded into the City dropdown. 我已经测试了SQL,它可以正常运行并检索我想要的值,但是由于某种原因,我无法弄清楚,这些值没有被层叠到City下拉列表中。

Any help is very much appreciated. 很感谢任何形式的帮助。

EDIT: As I'm doing more debugging and realizing a few things, this is what I've found so far. 编辑:由于我正在做更多的调试和实现一些事情,这就是我到目前为止发现的。 The JSON comes in like this: JSON如下所示:

[{"city":"Salt Lake City"},{"city":"Toole"},{"city":"Provo"},{"city":"St. George"}]

I now know the JSON is working correctly. 我现在知道JSON正常工作。 When I changed the dropdown selection in the state dropdown to a state that I know had entries for the cities, the city dropdown showed blank 'option' fields for the number of entries that there actually were. 当我将州下拉菜单中的下拉菜单更改为我知道有城市条目的状态时,城市下拉列表显示空白的“选项”字段来表示实际存在的条目数量。 So, using the answer below and MANY different tutorials on cascading dropdowns and chained dropdowns, I finally figured it out. 因此,使用下面的答案以及有关级联下拉列表和链接下拉列表的许多不同教程,我终于弄清楚了。 I've submitted an answer with the working code. 我已经提交了包含工作代码的答案。

Can you try: 你能试一下吗:

$.each(data, function(index, array){
    // new Option(text [, value, defaultSelected, selected]);
    select.add(new Option(array['city'], index), null);
});

?? ??

All of the code above worked except the jQuery function. 上面的所有代码均有效,但jQuery函数除外。 Well, the jQuery worked for what I told it to do, not for what I really wanted the code TO DO... Big difference. 好吧,jQuery是按照我告诉它要做的事情工作的,而不是我真正想要执行代码的工作。

Here's the working jQuery that populates the city dropdown based on a selection made in the state dropdown: 这是根据状态下拉列表中的选择填充城市下拉列表的有效jQuery:

<script>
function populateCityName(){
$.getJSON('state-names.php', {stateName: $('#stateName').val()},
    function(data){
        var html = '<option value="';
        var htmlEnd = '</option>';
        var options = '';
        var select = $('#cityName');
        $('option', select).remove();
        $.each(data, function(index, array){
            options += html + array['city'] + '">' + array['city'] + htmlEnd;
         });
        $('#cityName').append(options);
    });
}

$(document).ready(function(){
  populateCityName();
  $('#stateName').on('change', function(){
        populateCityName();
  });
});
</script>

Before, the code would find the number of entries and the select box would show this number, but the selections were blank. 以前,代码将找到条目数,并且选择框将显示该数字,但是选择为空白。 With this code, the number of entries is found, but the values for those entries also show. 使用此代码,可以找到条目数,但是也会显示这些条目的值。 Hope this helps someone else later. 希望以后能对其他人有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM