我正在向我的站点添加私有(private)消息。在我表单的收件人文本字段中,我想在有人开始输入时建议有效的用户名。在阅读了教程并研究了一些脚本之后,我编写了以下代码,用于从名为 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
},
});
});
Controller (为简单起见,我没有使用模型,尽管我计划使用)
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));
关于php - 我的 Codeigniter 使用 ajax 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6794089/