我在页面中有一组会话,我想使用AJAX将其删除。即,单击链接,而不必导航到新页面,只需删除会话,并在成功时显示一条消息。
现在,根据给定的答案( 对我仍然无效 ),我有以下内容:
控制者
use Symfony\Component\HttpFoundation\JsonResponse; //.. public function ajaxRemoveSessionAction() { $session = $this->getRequest()->getSession(); $session->remove('name'); return new JsonResponse(array('success' => true)); }
路由:
ajax_remove_session: pattern: /remove-session defaults: { _controller: FooTestBundle:Page:ajaxRemoveSession }
枝条:
<a href="#" id="remove_session">Remove session</a> <script type="text/javascript"> $(document).ready(function() { $('#remove_session').click(function(){ event.preventDefault(); $.ajax({ url: {{ url('ajax_remove_session') }}, cache: false, success: function(result){ $(".success").append(result); } }); }); }); </script>
带有在路由,控制器和模板中找到的所有代码
控制器:PageController.php
/src/Simon/TestBundle/Controller/PageController.php
<?php namespace Simon\TestBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Session\Session; use Symfony\Component\HttpFoundation\JsonResponse; class PageController extends Controller { public function helloAction($name) { $session = new Session(); $session->start(); $session->get('name', 'Drak'); $session->get('name'); $session->getFlashBag()->add('notice', 'Profile Updated'); $messages = null; foreach($session->getFlashBag()->get('notice', array()) as $message){ $messages = $message; } return $this->render('SimonTestBundle:Page:index.html.twig', array('name' => $name.' '.$messages)); } public function ajaxRemoveSessionAction() { // Destroy the desired session $session = $this->getRequest()->getSession(); $session->remove('name'); return new JsonResponse(array('success' => true)); } }
模板:细枝模板
/src/Simon/TestBundle/Resources/views/Page/index.html.twig
{% extends 'SimonTestBundle::layout.html.twig' %} {% block body %} <a href="#" id="remove_session">Remove session</a> <script type="text/javascript"> $('#remove_session').click(function(e){ e.preventDefault(); $.ajax({ url: {{ url('ajax_remove_session') }}, cache: false, success: function(html){ // do something on success } }).fail(function(event){ console.log(event); }); }); }); </script> {% endblock %}
/src/Simon/TestBundle/Resources/config/routing.yml
simon_test_homepage: pattern: /hello/{name} defaults: { _controller: SimonTestBundle:Page:hello } ajax_remove_session: pattern: /remove-session defaults: { _controller: SimonTestBundle:Page:ajaxRemoveSession }
尝试将URL选项的值放在引号之间:
url: '{{ url('ajax_remove_session') }}',