当我需要将用JavaScript检索到的一些参数传递给控制器中的方法时,我被AJAX/S2搞糊涂了。
在我的脚本中,我得到了位置var:
function handle_geolocation_query(position){
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(result1) {
console.log(result1);
});
};
function getLakes(lat, long) {
return $.ajax({
url: "{{ path('getLakes') }}",
data: { lat:lat, lng: lng },
dataType: 'jsonp'
});
};那么路由器就是这样设置的:
getLakes:
pattern: /lakes
defaults: { _controller: PondipGeolocBundle:Default:getLakesSurrounding }在我的控制器中,我应该返回一个数组:
public function getLakesSurrounding($lat=0, $lng=0, $limit = 50, $distance = 50, $unit = 'km')
{
$lat = $this->getRequest()->get('lat');
$lng = $this->getRequest()->get('lont');
$return= array( '1'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'2'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'3'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'4'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4'),
'5'=> array( 'title' => 'lake1',
'venue' => 'lake2',
'dist' => 'lake3',
'species' => 'lake4',
'stock' => 'lake4')
);
$return=json_encode($return); //jscon encode the array
return new Response($return,200,array('Content-Type'=>'application/json')); //make sure it has the correct content type
}然后,我想将它传递给另一个函数,该函数将设置带有小胡子的模板,以便在视图中打印它(我还没有在这里..)
我的问题是:我不能将所需的lat和long数据传递给我的函数。路由器变得疯狂,控制器得不到任何东西,我也不能从脚本中得到任何东西。编辑:我找到了传递变量的方法,但是我仍然不能从我的控制器得到任何响应,没有发生任何事情,$.when也没有执行任何回调
我是AJAX的新手,请指教。
发布于 2013-03-15 08:03:11
看看FOSJsRoutingBundle吧。通过它,您可以使用JS中的路由器:
Routing.generate('my_route_to_expose', { "id": 10, "foo": "bar" });https://stackoverflow.com/questions/15422393
复制相似问题