我正试图将坐标值从视图传递到控制器add
,该值取自地理定位谷歌api,但我遇到了一些问题。这是我在名为_add
的视图中使用的脚本。脚本之所以有效,是因为javascript控制台打印输出协调良好。
<script type="text/javascript">
$(document).ready(function(){
get_location();
});
function get_location()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position){
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.post('http://firstaid:8888/add', { latitude:latitude, longitude:longitude });
});
}
}
</script>
现在,我将通过这种方式将这些视图中的值传递给控制器,我可以将其用作php代码点火器控制器中的变量。为此,我使用$this->input->post
。
function index()
{
$data['title'] = 'Add';
$latitude = $this->input->post('latitude');
$this->load->view('templates/_header', $data);
$this->load->view('_add');
}
但当我打印出$latitude
时,变量为空。可能是哪里出了错?也许是因为我在加载视图之前打电话给post?
是否存在将数据传递给控制器的其他方式?
您需要更改此行:
$.post('http://firstaid:8888/add', { latitude:latitude, longitude:longitude });
到此:
$.post('http://firstaid:8888/add', 'latitude='+latitude+'&longitude='+longitude);
当然,有不止一种方法可以对猫进行剥皮,因为我相信有一种jQuery方法可以将JSON序列化为正确的POST变量字符串格式,但我在这里所做的肯定会奏效。
您没有向视图传递$latitude,因此无法访问它。
如果您正在加载一个新页面,$latitude将需要位于传递给视图的$data数组中。
但是,您使用的是Ajax,因此无法以这种方式加载新视图。你需要做一些类似的事情:
$latitude = $this->input->post('latitude');
echo json_encode( $latitude );
然后在您的Javascript中处理响应。
或者直接在控制器中使用print_r来确认变量是否存在。
print_r($this->input->post('latitude'));
在你的Javascript中试试这个:
$.ajax({
type: "POST",
url: "/add",
data: "latitude=" + latitude,
dataType: "json",
success: function(msg){
alert('Completed');
} //End success condition
}); //End ajax
在Chrome或Firebug中发出Ajax请求时,请确保"网络"面板处于打开状态,以便确认它正在找到您的控制器。
控制器文件:
$this->load->library('googlemaps');
$config['center'] = '37.4419, -122.1419';
$config['zoom'] = 'auto';
$this->googlemaps->initialize($config);
$marker = array();
$marker['position'] = '37.429, -122.1419';
$marker['draggable'] = true;
$marker['ondragend'] = 'updateDatabase(event.latLng.lat(), event.latLng.lng());';
$this->googlemaps->add_marker($marker);
$data['map'] = $this->googlemaps->create_map();
$this->load->view('view_file', $data);
视图文件:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
function updateDatabase(newLat, newLng)
{
// make an ajax request to a PHP file
// on our site that will update the database
// pass in our lat/lng as parameters
$.post(
"/my_controller/update_coords",
{ 'newLat': newLat, 'newLng': newLng, 'var1': 'value1' }
)
.done(function(data) {
alert("Database updated");
});
}
</script>
<?php echo $map['js']; ?>
</head>
<body><?php echo $map['html']; ?></body>
</html>
引用人:http://biostall.com/demos/google-maps-v3-api-codeigniter-library/updatedatabase