简体   繁体   English

jQuery级联与PHP和催化剂的下拉列表

[英]Jquery cascading dropdowns with php and catalyst

I am trying to implement cascading dropdown menus within a catalyst web app. 我正在尝试在催化剂Web应用程序中实现级联下拉菜单。 The objective is to select a database table in the first menu and have the columns in that table appear in the second menu. 目的是在第一个菜单中选择一个数据库表,并使该表中的列出现在第二个菜单中。 My strategy is to use Jquery with a PHP helper script to run the query against the database. 我的策略是将Jquery与PHP帮助程序脚本一起使用,以对数据库运行查询。

Jquery code: jQuery代码:

$("#db_table").change(function() {
    console.log("dbtable changed");
    $("#db_field").load("[% c.uri_for('/field_get.php')%]?choice=" + $("#db_table").val());
});

PHP: PHP:

<?php
    $username = "webuser";
    $password = "webuser";
    $hostname = "localhost";

    $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
    $selected = mysql_select_db("mousesom", $dbhandle) or die("Could not load database");
    $choice = mysql_real_escape_string($_GET['choice']);

    $query = "SELECT column_name FROM information_schema.columns WHERE table_name = '$choice';";

    $result = mysql_query($query);

    while ($row = mysql_fetch_array($result)) {
        echo "<option>" . $row{'dd_val'} . "</option>";
    }
?>

HTML: HTML:

Table:<select id="db_table">
   <option selected value="base">Choose a Table</option>
   <option value="neurons">Neurons</option>
   <option value="peaks_factors">Transcription Factors</option>
   <option value="peaks">Peaks</option>
   <option value="peaks_selection">Selection</option>
   <option value="peaks_histmods">Histone Modification</option>
</select>
Field:<select id="db_field">
   <option value="Placeholder">Please Select a Table</option>
</select>

I have thus far verified that the javascript request is firing, but I am not getting the expected response. 到目前为止,我已经验证了javascript请求正在触发,但是没有得到预期的响应。 Based on the log output from the Catalyst test server, it seems most likely the needed arguments are not being passed to the PHP helper script, instead being split off into query params by Catalyst instead... 根据Catalyst测试服务器的日志输出,似乎很有可能没有将所需的参数传递给PHP帮助程序脚本,而是由Catalyst拆分为查询参数。

[info] *** Request 8 (0.013/s) [17122] [Fri Jun 26 19:22:50 2015] ***
[debug] Path is "/"
[debug] Arguments are "field_get.php"
[debug] "GET" request for "field_get.php" from "10.21.136.40"
[debug] Query Parameters are:
.-------------------------------------+--------------------------------------.
| Parameter                           | Value                                |
+-------------------------------------+--------------------------------------+
| choice                              | peaks_histmods                       |
'-------------------------------------+--------------------------------------'

Clearly this is not what I want to happen and am wondering if Catalyst has another way of passing these params to the helper script or some other workaround. 显然,这不是我想要发生的事情,并且我想知道Catalyst是否具有将这些参数传递给辅助脚本或其他解决方法的另一种方法。 I've been searching various documentations and have, thus far, come up empty-handed. 我一直在搜索各种文档,到目前为止,都是空手而归。 Any help would be appreciated! 任何帮助,将不胜感激!

Your request is being handled as if it's a Catalyst action because you're telling it to when you use the template code [% c.uri_for() %] . 您的请求就像是Catalyst操作一样被处理,因为您是在告诉您何时使用模板代码[% c.uri_for() %] If you're going to call a PHP script, it needs to be outside the Catalyst URI namespace, perhaps by putting it amongst your root/static resources, or somewhere else your webserver expects to find PHP resources. 如果您要调用PHP脚本,则该脚本必须位于Catalyst URI命名空间之外,可能是通过将其放在您的root/static资源中,或者您的网络服务器希望在其他地方找到PHP资源。

Having said that, I do not understand why you would introduce PHP into this mix. 话虽这么说,但我不明白为什么要将PHP引入此组合。 A Catalyst controller that returns the list of column names should be trivial to implement. 返回列名列表的Catalyst控制器应该很容易实现。 The following untested code assumes you have a database handle available in your Catalyst app called $dbh . 以下未经测试的代码假定您在Catalyst应用程序中有一个名为$dbh的数据库句柄。 Whatever DB abstraction layer you're using (DBIC?), there's a straightforward way to get this. 无论您使用的是什么数据库抽象层(DBIC?),都有一种直接的方法来实现。 You might also choose to create proper model code for this. 您可能还选择为此创建适当的模型代码。

sub get_fields :Args(1) {
    my ($self, $c, $table) = @_;
    my $qry = "SELECT column_name FROM information_schema.columns WHERE table_name = ?";
              # we'll have none of that nasty SQL injection-vulnerable code here...
    my $result = "";
    my @res = $dbh->selectall_arrayref($qry, { Slice=>{} }, $table );
    map { $result .= sprintf("<option>%s</option>", $_->{column_name} } @res;
    $c->res->body($result);
}

I will be the first to point out that this approach is not best-practice, but it might give you some ideas about how this should be done. 我将是第一个指出这种方法不是最佳实践的人,但是它可能会给您一些有关如何进行的想法。 (Hint: a better practice would be to return the column names as JSON, and handle creating <option> tags in jQuery, rather than creating a HTML snippet in your Catalyst Action. Because you might find a method that accepts a table name and returns its columns might be generically useful.) (提示:更好的做法是将列名称返回为JSON,并处理在jQuery中创建<option>标记,而不是在Catalyst Action中创建HTML代码段。因为您可能会找到一个接受表名并返回的方法其列可能通常有用。)


Update 更新资料

You can use Catalyst::View::JSON, and by putting your list of columns into $c->stash->{json} , it will Do The Right Thing, even if it is overkill for the use-case. 您可以使用Catalyst :: View :: JSON,然后将列列表放入$c->stash->{json} ,即使使用情况过大,它也会做正确的事。 You can also just convert to JSON and return it in $c->res->body() : if that is not empty, all template processing is bypassed. 您也可以只转换为JSON并在$c->res->body()返回它:如果不为空,则将跳过所有模板处理。 So what you need might be as simple as: 因此,您所需要的可能很简单:

use JSON;

sub get_fields :Args(1) {
    my ($self, $c, $table) = @_;
    my @rows = $c->model('InformationSchema')->result_set('Columns')->search({table_name => $table});
    my $columnlist = [ map { $_->column_name } @rows ];
    $c->res->body(to_json($columnlist));
}

... but a bit more error-checking would be no bad thing. ...但是更多的错误检查将不是一件坏事。

Accessing from jQuery boils down to something like (again, untested): 从jQuery的访问归结为类似(再次未经测试):

$("#db_table").change(function() {
    $.ajax({
        type: "GET",
        url: "[% c.uri_for('/__your_module__/get_fields/') %]" + $("#db_table").val(),
        success: function(json){
            $.each(json, function(i, val) {
                $('#db_field').append($('<option>').text(val).attr('value', val));
            });
        }
    });
});

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

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