doushi1900 2015-06-26 19:50
浏览 56
已采纳

与php和催化剂的Jquery级联下拉列表

I am trying to implement cascading dropdown menus within a catalyst web app. 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 code:

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

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:

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. 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...

[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. I've been searching various documentations and have, thus far, come up empty-handed. Any help would be appreciated!

  • 写回答

1条回答 默认 最新

  • duankao4489 2015-06-29 05:31
    关注

    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() %]. 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.

    Having said that, I do not understand why you would introduce PHP into this mix. A Catalyst controller that returns the list of column names should be trivial to implement. The following untested code assumes you have a database handle available in your Catalyst app called $dbh. Whatever DB abstraction layer you're using (DBIC?), there's a straightforward way to get this. 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.)


    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. You can also just convert to JSON and return it in $c->res->body(): if that is not empty, all template processing is bypassed. 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):

    $("#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));
                });
            }
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于温度改变石墨烯介电性能(关键词-介电常数)
  • ¥150 HDMI分路器LT86102 的输出在890MHz频点处EMC超标8DB
  • ¥15 druid(相关搜索:数据库|防火墙)
  • ¥15 大一python作业
  • ¥15 preLaunchTask"C/C++: aarch64- apple-darwin22-g++-14 生成活动 文件”已终止,退出代码为-1。
  • ¥60 如何鉴定微信小程序数据被篡改过
  • ¥18 关于#贝叶斯概率#的问题:这篇文章中利用em算法求出了对数似然值作为概率表参数,然后进行概率表计算,这个概率表是怎样计算的呀
  • ¥20 C#上传XML格式数据
  • ¥15 elementui上传结合oss接口断点续传,现在只差停止上传和继续上传,各大精英看下
  • ¥20 手机截图相片分辨率降低一半