我正在添加私人消息到我的網站。在我的表單中的收件人文本字段中,我想在有人開始輸入時提示有效的用戶名。在閱讀教程和學習一些腳本之後,我提出了以下代碼,用於從名爲users的數據庫表中建議用戶名。它有效,但我不確定它是多麼正確和安全。我的Codeigniter自動完成與阿賈克斯
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);
}
好的提示!謝謝! – CyberJunkie