php – 我的Codeigniter使用ajax自动完成

我正在为我的网站添加私人消息.在我的表单中的“收件人”文本字段中,我想在有人开始键入时建议有效的用户名.在阅读了教程并研究了一些脚本后,我制作了以下代码,用于建议我的数据库表中名为users的用户名.它有效,但我不确定它是多么正确和安全.

Jquery(使用Jquery UI自动完成插件):

$(function() {                     
    $( "#username" ).autocomplete({ //the recipient text field with id #username
        source: function( request, response ) {
            $.ajax({
                url: "http://localhost/mysite/index.PHP/my_controller/search_username",
                dataType: "json",
                data: request,
                success: function(data){
                    if(data.response == 'true') {
                       response(data.message);
                    }
                }
            });
        },
        minLength: 1,
        select: function( event, ui ) {
            //Do something extra on select... Perhaps add user id to hidden input    
        },

    });
}); 

控制器(为简单起见,我没有使用模型,虽然我计划)

function search_username()
{
        $username = trim($this->input->get('term')); //get term parameter sent via text field. Not sure how secure get() is

        $this->db->select('id, username'); 
        $this->db->from('users');
        $this->db->like('username', $username);
        $this->db->limit('5');
        $query = $this->db->get();

        if ($query->num_rows() > 0) 
        {
            $data['response'] = 'true'; //If username exists set true
            $data['message'] = array(); 

            foreach ($query->result() as $row)
            {
                $data['message'][] = array(  
                    'label' => $row->username,
                    'value' => $row->username,
                    'user_id'  => $row->id
                );
            }    
        } 
        else
        {
            $data['response'] = 'false'; //Set false if user not valid
        }

        echo json_encode($data);
} 

解决方法:

我建议制作一个编辑…

我会通过将第二个参数TRUE传递给get()来启用XSS保护

    $username = trim($this->input->get('term', TRUE));

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...