我刚开始学习如何在Codeigniter中使用AJAX。在我的视图中,我有一个textarea和一个按钮,它使用AJAX将文本区域中的文本提交给我的控制器,控制器从数据库中检索数据并将这些数据返回给视图。但是,我在回调函数中得到了“不允许的键字符”错误。即使我只是简单地echo
一个字符串,也会发生这种情况。这是怎么回事?
顺便说一句,我应该在控制器中使用return $result
或echo $result
将数据传递回网页吗?
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.get('index.php/main/get_places', search_location, function(data){
$("#result").html(data);
console.log(data);
});
});
});
控制器
function get_places($address) {
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo "test";
}
发布于 2011-10-18 02:03:01
CodeIgniter将url中的字符限制为:
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; //Inside config.php
在发送AJAX请求时,您可能会在地址中添加不在此列表中的字符。我的建议是将$.get
更改为$.post
,然后在控制器中获取post数据。就像这样:
AJAX
$(function() {
$("#search_button").click(function(e){
e.preventDefault();
var search_location = $("#search_location").val();
$.post('index.php/main/get_places', {'search_location': search_location}, function(data){
$("#result").html(data);
console.log(data);
});
});
});
控制器
function get_places() {
$address = $this->input->post('search_location');
$search_latlng = $this->geocode_address($address);
$this->load->model('main_model.php');
$result = $this->main_model->get_places($search_latlng);
echo $result;
}
至于echo
vs return
,请使用echo
。
发布于 2011-10-18 02:04:28
您可能不允许在url中使用查询字符串,而Ajax函数将查询字符串添加到URL中。看看下面的url,了解如何打开查询字符串:
http://www.askaboutphp.com/58/codeigniter-mixing-segment-based-url-with-querystrings.html
https://stackoverflow.com/questions/7801566
复制相似问题