我在一个页面中有一组会话,我想使用 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 }