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 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。