依赖/级联下拉列表

时间:2014-02-19 15:50:47

标签: javascript php jquery json get

我正在使用级联下拉列表jquery插件。 (https://github.com/dnasir/jquery-cascading-dropdown

我有两个下拉菜单。 '客户'和'网站'。

根据您选择的客户端,应适当缩小网站列表,以仅显示所选客户端的网站。我已经设置了两个php脚本returnClientList.php和returnSiteList.php,它们成功返回带有标签/值对的json数组。

我的问题是,在选择客户端后,我无法减少网站列表。事件成功触发,但我只收回完整列表。正如您将看到的,代码正在使用getJSON请求,我从手册中了解到发送HTTP GET。查看chrome的 network 面板显示实际上没有发送GET值。

希望显而易见的事情,但我是jquery的新手,所以帮助赞赏。

我的代码:

JS

$('#edit-shift').cascadingDropdown({
selectBoxes: [
    {
      selector: '.clients',
      source: function(request, response) {
      $.getJSON('returnClientList.php', request, function(data) {
                  var selectOnlyOption = data.length <= 1;
                  response($.map(data, function(item, index) {
                      return {
                          label: item.label,
                          value: item.value,
                          selected: selectOnlyOption // Select if only option
                      };
                  }));
              });
          }
    },
    {
        selector: '.sites',
        requires: ['.clients'],
        source: function(request, response) {
            $.getJSON('returnSiteList.php', request, function(data) {
                var selectOnlyOption = data.length <= 1;
                response($.map(data, function(item, index) {
                    return {
                        label: item.label,
                        value: item.value,
                        selected: selectOnlyOption // Select if only option
                    };
                }));
            });

        }
    },
    {
        onChange: function(event, value, requiredValues){}
    }
]
});

PHP

//this script returns a json array for use in jquery autocomplete fields for site     lists...
header('Content-type: application/json');
require("connect.php");

$client_id = $_GET['?'];

 //do the query for sites that are active
$sql =  "SELECT * FROM site WHERE active=1 AND client_id='$client_id' ORDER BY site_name ASC";
$result = mysql_query($sql) or die('Error: ' . mysql_error());

//loop the results and create php array
while($row = mysql_fetch_array($result)){
    $arr[] = array('label' => $row['site_name'], 'value' => $row['id']);
}

echo json_encode($arr);

1 个答案:

答案 0 :(得分:0)

结束编写我自己的解决方案并取消插件。请享用。

//dynamically returns the sites once the user chooses a client - edit/add shift form
  $('.client-id').change(function () {
    var selectedClient = $(this).val();
    if (selectedClient != null && selectedClient != '') {

        $.getJSON('returnSiteList.php', { id: selectedClient }, 
                    function (Sites) {
                      var siteSelect = $('.site-id');
                      siteSelect.empty();
                      $.each(Sites, function (index, site) {
                      siteSelect.append($('<option/>', {
                      value: site.value,
                      text: site.label
                }));
            });
        });
    }
});
相关问题