【问题标题】:How to implement Ajax in Symfony2如何在 Symfony2 中实现 Ajax
【发布时间】:2015-11-20 00:01:47
【问题描述】:

我的 Symfony2 项目中有一个基本但功能强大的搜索机制。这将使用 Doctrine2 LIKE 表达式查询并向用户显示数据。但我想通过添加更“动态”和更“用户友好” Ajax 功能。我在控制器中添加了一些 Ajax 代码,但我不知道如何使其工作。图像加载器只是“旋转”而不显示结果。

//controller

public function searcAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $query = $this->getRequest()->get('query');

    if(!$query) {
        if(!$request->isXmlHttpRequest()) {
            return $this->redirect($this->generateUrl('voters_list'));
        } else {
            return new Response('No results.');
        }
    }

    $city = $em->getRepository('DuterteBundle:City')->findCity($query);

    if($request->isXmlHttpRequest()) {
        if('*' == $query || !$city || $query == '') {
            return new Response('No results.');
        }
        //display a another page
        return $this->render('DuterteBundle:City:list1.html.twig', array('city' => $city));
    }

    return $this->render('DuterteBundle:City:search.html.twig', array('city' => $city));
}

// 路由

search:
path: /search
defaults: { _controller:DuterteBundle:City:Searc }
requirements:


//search.html.twig

{% extends '::base.html.twig' %}

{% block body %}
<div id="city">
    {% include 'DuterteBundle:City:list1.html.twig' with {'city': city} %}
</div>
{% endblock %}

//list1.html.twig

{% block body %}
<div class="page-header">
    <h4>City/Municipality/Town and Its Corresponding Numbers of Voters</h4>
</div>
<table class="table table-hover table-bordered table-condensed">
    <thead>
        <tr>
            <th>City</th>
            <th>Votes</th>
            <th>Percent</th>
        </tr>
    </thead>
    <tbody>
        {% for city in city %}
        <tr>
            <td>{{ city }}</td>
            <td>{{ number_votes_city(city.id) }}</td>
            <td></td>
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}

我的搜索表单嵌入在主布局的导航栏中。

<div class="col-sm-3 col-md-3" id="search">
<form class="navbar-form" role="search" action ="{{ path('search')}}" method ="post">
 <div class="input-group">
 <input type="text" class="form-control" placeholder="Search city/town" name="query" value="{{ app.request.get('query') }}" id="search_keywords">
 <div class="input-group-btn">
   <button class="btn btn-default" type="submit"><i class="fa fa-search"></i></button>
  <img id="loader" src="{{ asset('bundles/duterte/images/loader.gif') }}" style="vertical-align: middle; display: none" />
 </div>
 </div>
</form>

//repository

public function findCity($city)
{

    return $this
        ->createQueryBuilder('c')
        ->select('c')
        ->where('c.name LIKE :name_city')
        ->setParameter('name_city', '%'.$city.'%')
        ->orderBy('c.name', 'ASC')
        ->getQuery()
        ->getResult()
    ;
}

最后是js文件

 $(document).ready(function()
            {
                $('.search input[type="submit"]').hide();
                $('#search_keywords').keyup(function(key)
                {
                    if(this.value.length >= 3 || this.value == '') {
                        $('#loader').show();
                        $('#city').load(
                            $(this).parent('form').attr('action'),
                            { query: this.value ? this.value + '*' : this.value },
                            function() {
                                $('#loader').hide();
                            }
                        );
                    }
                });
            });

感谢任何帮助

【问题讨论】:

  • 日志文件有错误吗?

标签: php ajax symfony


【解决方案1】:

功能相同,但方法不同。监听搜索框上的 keyup 事件 然后对控制器进行 ajax 调用,该控制器将匹配结果列表作为 json 返回。检查响应和 根据响应的状态,隐藏现有列表并将其内容替换为返回的标记 AJAX 调用的 json 响应。

这里的例子是在用户列表中搜索。

  1. 树枝文件上的表格标记

    <div id="user-list-div">
     <table class="records_list" id="user-list">
    <thead>
    <tr>
        <th>Id</th>
        <th>Name</th>
        <th>Username</th>
        <th>Password</th>
        <th>Salt</th>
        <th>Email</th>
        <th>Isactive</th>
        <th>Createdat</th>
        <th>Updatedat</th>
        <th>Isbillableuser</th>
        <th>Isdeleted</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody id = "user-table">
    {% for entity in entities %}
        <tr>
            <td><a href="{{ path('admin_user_show', { 'id': entity.id }) }}">{{ entity.id }}</a></td>
            <td>{{ entity.name }}</td>
            <td>{{ entity.username }}</td>
            <td>{{ entity.password }}</td>
            <td>{{ entity.salt }}</td>
            <td>{{ entity.email }}</td>
            <td>{{ entity.isActive }}</td>
            <td>{% if entity.createdAt %}{{ entity.createdAt|date('Y-m-d H:i:s') }}{% endif %}</td>
            <td>{% if entity.updatedAt %}{{ entity.updatedAt|date('Y-m-d H:i:s') }}{% endif %}</td>
            <td>{{ entity.isBillableUser }}</td>
            <td>{{ entity.isDeleted }}</td>
            <td>
                <ul>
                    <li>
                        <a href="{{ path('admin_user_show', { 'id': entity.id }) }}">show</a>
                    </li>
                    <li>
                        <a href="{{ path('admin_user_edit', { 'id': entity.id }) }}">edit</a>
                    </li>
                </ul>
            </td>
        </tr>
    {% endfor %}
    </tbody>
    

  2. 搜索表单标记

    <div class="col-lg-6">
        <div class="input-group">
            <input type="text" class="form-control" id="search-field">
        <span class="input-group-btn">
            <button class="btn btn-default" type="button">Go!</button>
         </span>
         </div>
     </div>
    
  3. javascript部分

    <script>
        $(function(){
            console.log('desperate for');
    
            var searchField = $('#search-field');
            var userTable = $('#user-table');
            var userListDiv = $('#user-list-div');
    
            searchField.keyup(function(evt){
                console.log($(this).val());
    
                $.ajax({
                    url: '{{ path('admin_user_search') }}',
                    method: "POST",
                    data: "id=" + $(this).val() ,
                    dataType: 'html',
                    success: function(result, request) {
    
                      var parsedData =JSON.parse(result);
                        console.log(parsedData);
                        if(parsedData.status ==='success'){
                            console.log('hete');
                            userListDiv.empty();
                            userListDiv.html(parsedData.data);
                        }else{
                            //handle no result case
                        }
                    }
                });
            });
        });
    </script>
    
  4. ajax_template.html.twig 文件

与上面给出的相同的表格标记

  1. 控制器动作

    公共函数 searchuserAction(){ $em = $this->getDoctrine()->getManager(); $request = $this->get('request');

        $searchParameter = $request->request->get('id');
    
        //call repository function
    
        $entities = $em->getRepository('LBCoreBundle:User')->findUsersForname($searchParameter);
        $status = 'error';
        $html = '';
        if($entities){
            $data = $this->render('LBCoreBundle:User:ajax_template.html.twig', array(
                'entities' => $entities,
            ));
            $status = 'success';
            $html = $data->getContent();
        }
    
    
        $jsonArray = array(
            'status' => $status,
            'data' => $html,
        );
    
        $response = new Response(json_encode($jsonArray));
        $response->headers->set('Content-Type', 'application/json; charset=utf-8');
    
        return $response;
    }
    
  2. 存储库函数

    public function findUsersForname($name){
        $em = $this->getEntityManager();
    
        $query = $em->createQuery("SELECT e FROM LBCoreBundle:User e
                 WHERE e.username LIKE '%$name%'");
    
        $entities = $query->getResult();
        return $entities;
    
    }
    

【讨论】:

  • @Pravesh 这种方法不会像表格一样返回我的表单。相反,它会以 json 格式返回所有标记和数据
  • 客户端 javascript 应该将 Ajax 调用返回的 html 标记插入到您的列表页面中。
猜你喜欢
  • 2015-10-17
  • 1970-01-01
  • 2017-07-29
  • 2021-06-15
  • 2016-03-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
相关资源
最近更新 更多