简体   繁体   English

Symfony2,创建ajax请求

[英]Symfony2, Create ajax request

I have created an action his role is to display the data by an order according to the selected choice. 我创建了一个动作,他的作用是根据选定的选择按顺序显示数据。

This is the twig page: list.html.twig 这是树枝页面: list.html.twig

<script type="text/javascript">
function sendForm() {
var sort_list = document.getElementById("sort_list").value;
if (sort_list) { // if is OK
document.getElementById("myForm").submit(); // submit form
}
}
</script>


        <!-- sorting, pages -->

        <form action="" method="post" class="form_sort" id="myForm">
          <span class="manage_title">Sort by:</span>
            <select class="select_styled white_select" id="sort_list" name="orderBy" onChange="sendForm();">
                <option value="country:asc">Country A-Z</option>
                <option value="country:desc">Country Z-A</option>
                <option value="destination:asc">City A-Z</option>
                <option value="destination:desc">City Z-A</option>
             </select>
        </form>    

            {% for travel in listTravels %}

            <div class="re-item">           
                <div class="re-image">
                    <a href="{{ path('frontend_view', {'slug': travel.slug} ) }}"><img src="{{ asset(travel.image.webPath) }}" alt="{{ travel.slug }}"  /><span class="caption">View Details</span></a>
                </div>
            //***********

          </div>

         {% endfor %}

and this is the action in the controller 这是控制器中的动作

    public function listAction($page, Request $request)
{
    $em = $this->getDoctrine()->getManager();

    $nbByPage = $this->container->getParameter('travel.number_by_page');
    $orderBy = "id:desc"; // set default order

    if ($request->getMethod() == 'POST')
    {
        if(isset($_POST['orderBy']))
        {
            $orderBy = $_POST['orderBy'];
        }

    }

    $listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend($nbByPage, $page, $orderBy);

    return $this->render('ProjectFrontendBundle:Frontend:list.html.twig',
    array(
        'listTravels' => $listTravels,
        'page'     => $page,
        'nb_page'  => ceil(count($listTravels) / $nbByPage) ?: 1
    ));
}

This code works but it reloads the page every time when user select a choice, can you help me do this action with ajax? 这段代码有效,但是每次用户选择一个选项时它都会重新加载页面,您能帮我用Ajax进行此操作吗?

This is the route : 这是路线:

frontend_list:
path:     /travels
defaults: { _controller: ProjectFrontendBundle:Frontend:list }

Another question is should I create another route and add a parameter "order" or using the same route ? 另一个问题是我应该创建另一条路线并添加参数“ order”还是使用同一条路线?

So I would try something like this : 所以我会尝试这样的事情:

Twig 枝条

<script type="text/javascript">
function refresh() {
  $.ajax({
    type: "POST",
    url: Routing.generate('frontend_list'), // If you're not using FOSJsRoutingBundle,
                                            // just use the path here
    data: { orderBy: $('#orderBy').val() }
  })
  .done(function(data) {
    // Just parse your data here and put it in your HTML
  });
}
</script>


<!-- sorting, pages -->

<form action="" method="post" class="form_sort" id="myForm">
  <span class="manage_title">Sort by:</span>
    <select class="select_styled white_select" id="sort_list" name="orderBy" onChange="refresh();">
        <option value="country:asc">Country A-Z</option>
        <option value="country:desc">Country Z-A</option>
        <option value="destination:asc">City A-Z</option>
        <option value="destination:desc">City Z-A</option>
     </select>
</form>    

{% for travel in listTravels %}
  <div class="re-item">           
      <div class="re-image">
          <a href="{{ path('frontend_view', {'slug': travel.slug} ) }}"><img src="{{ asset(travel.image.webPath) }}" alt="{{ travel.slug }}"  /><span class="caption">View Details</span></a>
      </div>
  </div>
{% endfor %}

Here, I used jQuery to perform an Ajax request which is gonna get a JSON response from the server, you're gonna have to parse and format that response in order to show it properly on the page. 在这里,我使用jQuery执行一个Ajax请求,该请求将从服务器获取JSON响应,您将必须解析和格式化该响应,以便在页面上正确显示它。 Ajax request's target URL can be an absolute URL but I'd recommend using FOSJsRoutingBundle . Ajax请求的目标URL可以是绝对URL,但我建议使用FOSJsRoutingBundle

PHP 的PHP

<?php
public function listAction($page) {
    $em = $this->getDoctrine()->getManager();
    $request = $this->getRequest();

    $nbByPage = $this->container->getParameter('travel.number_by_page');
    $orderBy = "id:desc"; // set default order

    if ($request->getMethod() === 'POST' && isset($request->request->get('orderBy'))) {
        $orderBy = $request->request->get('orderBy');
    }

    $listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListTravelsFrontend($nbByPage, $page, $orderBy);

    if ($request->getMethod() === 'POST') {
        return json_encode($listTravels); // If the request was sent by Ajax, just JSON encode the data and return it
    }

    return $this->render('ProjectFrontendBundle:Frontend:list.html.twig',
    array(
        'listTravels' => $listTravels,
        'page'     => $page,
        'nb_page'  => ceil(count($listTravels) / $nbByPage) ?: 1
    ));
}

This is pretty much the same thing as you did, except that if the request is of type POST, then you can just return the data and let Javascript handle it client-side. 这几乎与您做的一样,不同之处在于,如果请求的类型为POST,则可以只返回数据并让Javascript在客户端进行处理。

I didn't test my code, I just wanted to show you the big picture. 我没有测试我的代码,我只是想向您展示全局。 You're probably gonna have to make some adjustments so it fits your needs. 您可能需要进行一些调整才能适合您的需求。 Concerning your question about the route, wether it should contain an order parameter or not is up to you. 关于您的路线问题,是否应包含order参数取决于您。 I guess it would make it easier to share search results. 我想这将使共享搜索结果更加容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM