0

我正在尝试使用 typeahead.js Twitter Typeahead(而不是 Bootstrap typeahead)来显示使用 CodeIgniter 框架从 mysql 表中提取的名称。该模型还收集 id 值和名称。

控制器和模型似乎呈现了正确的数组格式。

模型

class People_model extends CI_Model{

   function __construct() {
        parent::__construct();
   }
    function get_person($name) {
        $mode = $this->uri->segment(3);

        $this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
        $this->db->from('people');
        if($mode == 'signin')
            $this->db->where("status !=", "enter");
        else
            $this->db->where("status", "enter");
        $this->db->like("concat(firstName,' ', lastName)", $name);
        $this->db->order_by('name');
        $query = $this->db->get();
        if($query->num_rows > 0){
            foreach ($query->result_array() as $row){
            $new_row['value']=htmlentities(stripslashes($row['name']));
            $new_row['id']=htmlentities(stripslashes($row['id']));
            $row_set[] = $new_row; //build an array
            }
        }
        echo json_encode($row_set); //format the array into json data
    }
}

控制器(相关功能)

    function get_person() {
        $this->config->set_item('disable_template', TRUE);
        $this->load->model('People_model');
        $name = $this->input->get_post();
        $this->People_model->get_person($name); 
    }

    function dosigninout() {
        $mode = $this->uri->segment(3);
        switch($mode) {
            case 'signin':
                $mode = 'enter';
                break;
            case 'signout':
                $mode = 'exit';
                break;
            default:
                $this->load->view("home/error", array('error' => "Invalid mode specified."));
        }
        $meeting = $this->_currentMeeting();
        $person = $this->input->post('person_id');    
        if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));

        $this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
        $this->db->where("id", $person);
        $this->db->update("people", array('status' => $mode));
        $redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
        if($redirectTo) redirect($redirectTo);
        else redirect('attendance');
    }

返回的示例 JSON 数据

[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]

看法

$baseURL = base_url();
$extraHeadData = "";

?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
        <fieldset>
        <legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
        <div class="control-group">
            <div class="controls">
                <input type="hidden" name="person_id" id="person_id" value="" />
                <input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
            </div>
        </div>
        </fieldset>
        <div class="form-actions">
            <?=form_submit('','Save changes','class="btn btn-primary"'); ?>
        </div>
</form>

<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>

<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>

<script>
$(function($) {
    $('input.people-typeahead').typeahead({
        name: 'people',                                                             
        remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
        dataType: 'json'                                                                        
    });
    $("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) { 
        $(person_id).val() = datum.id
        });
});
</script>

In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. 我几乎可以肯定这是视图中的 javascript 代码不正确的问题,但坦率地说,我没有 js 技能来解决它​​!

4

2 回答 2

0

我在这里看到一个问题:

        $(person_id).val() = datum.id

您错误地使用了 jQuery 的 .val() 并且选择器的使用也是错误的。它应该看起来像:

$("#person_id").val(datum.id);  

jQuery .val() 文档

于 2013-06-24T03:11:01.520 回答
0

我终于想出了如何让这个工作。部分问题是我找不到在 CodeIgniter 中使用 typeahead.js 的示例来展示各种脚本、视图、控制器和模型组件如何交互。我尝试切换到 Twitter bootstrap typeahead。然而,尽管找到了将它与数组而不是字符串一起使用的引用,但我仍然无法获得有效的解决方案。

最后,我回到了 Twitter 上,从头开始。我发现本教程帮助很大:

Twitter Bootstrap typeahead.js 与 underscore.js 模板 - 教程 - Alan Greenblatt

我发布了对我有用的东西,以防它可以帮助其他有类似问题的人。此版本还包括将远程源设置为允许我通过 PHP 定义它的变量,以便我可以根据 URL 选择模型中的数据。

模型

class People_model extends CI_Model{

function __construct() {
    parent::__construct();
}
function get_person($name) {
    $modeinout = $this->uri->segment(3); 
    $this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
    $this->db->from('people');
    if($modeinout == 'signin'){
        $this->db->where('status !=', 'enter');
    }        
    else {
        $this->db->where('status', 'enter');
    }       
    $this->db->like("concat(firstName,' ', lastName)", $name);
    $this->db->order_by('name');
    $query = $this->db->get();
    if($query->num_rows > 0){
        foreach ($query->result_array() as $row){
            $new_row['name']=htmlentities(stripslashes($row['name']));
            $new_row['id']=htmlentities(stripslashes($row['id']));
            $row_set[] = $new_row; //build an array
        }
    }
    echo json_encode($row_set); //format the array into json data
}

控制器(相关功能)

function signin() {
    $this->load->helper("form");
    $this->template->javascript('assets/js/underscore-min.js');
    $this->template->javascript('assets/js/typeahead.min.js');
    $data = $this->_currentMeeting();
    $data['title'] = "Sign Someone In";
    $data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
    $data['mode'] = 'signin';
    $this->load->view("home/attendance/signinout", $data);
    }   

function signout() {
    $this->load->helper("form");
    $this->template->javascript('assets/js/underscore-min.js');
    $this->template->javascript('assets/js/typeahead.min.js');
    $data = $this->_currentMeeting();
    $data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
    $data['id'] = '';
    $data['title'] = "Sign Someone Out";
    $data['mode'] = 'signout';
    $this->load->view("home/attendance/signinout", $data);

}
function get_people() {
    $this->config->set_item('disable_template', TRUE);
    $this->load->model('People_model');
    $name = $this->input->post('query');
    $this->People_model->get_person($name);
}

function dosigninout() {
    $mode = $this->uri->segment(3);
    switch($mode) {
        case 'signin':
            $mode = 'enter';
            break;
        case 'signout':
            $mode = 'exit';
            break;
        default:
            $this->load->view("home/error", array('error' => "Invalid mode specified."));
    }
    $meeting = $this->_currentMeeting();
    $person = $this->input->post('person_id');
    if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
    $this->db->insert("attendance", array('person_id' => $person, 'meeting_id' =>      $meeting['meetingID'], 'type' => $mode));
    $this->db->where("id", $person);
    $this->db->update("people", array('status' => $mode));
    $redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
    if($redirectTo) redirect($redirectTo);
    else redirect('attendance');
}

看法

<?php
$baseURL = base_url();
$extraHeadData = "";

?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
        <fieldset>
        <legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
        <div class="control-group">
            <div class="controls">
                        <input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
            </div>
        </div>
        </fieldset>
        <div class="form-actions">
            <?=form_submit('','Save changes','class="btn btn-primary"'); ?>
        </div>
</form>   
<script>
    var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
   $(function($) {    
      _.compile = function(templ) {
         var compiled = this.template(templ);
         compiled.render = function(ctx) {
            return this(ctx);
         }
         return compiled;
      }
      $('.person-typeahead').typeahead({
         template: '<p><strong><%= name %></strong>:&nbsp;<%= id %></p>',
         name: 'people',
         valueKey: 'name',
         engine: _,
         remote: (person_url),
         dataType: 'json'
      }).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
         $('#person_id').val(datum.id);
         $('#person_name').val(datum.name);


        });
   });
</script>
<?=jquery_validate('attendance/signout');?>
于 2013-07-11T19:29:32.040 回答