Symfony2,创建ajax请求

时间:2014-11-23 14:58:09

标签: php ajax symfony doctrine-orm

我创建了一个动作,他的角色是根据所选择的选择按订单显示数据。

这是一个小页面: 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 %}

这是控制器

中的操作
    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
    ));
}

此代码有效,但每当用户选择一个选项时它会重新加载页面,你能帮我用ajax做这个动作吗?

这是路线:

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

另一个问题是我应该创建另一条路线并添加参数“order”还是使用相同的路线?

1 个答案:

答案 0 :(得分:0)

所以我会尝试这样的事情:

<强>枝条

<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 %}

在这里,我使用jQuery来执行Ajax请求,该请求将从服务器获得JSON响应,您将不得不解析并格式化该响应,以便在页面上正确显示它。 Ajax请求的目标URL可以是绝对URL,但我建议使用FOSJsRoutingBundle

<强> 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
    ));
}

这与你做的几乎完全相同,只是如果请求是POST类型,那么你可以只返回数据并让Javascript在客户端处理它。

我没有测试我的代码,我只想向您展示全局。您可能需要进行一些调整,以满足您的需求。 关于你关于路线的问题,它应该包含一个order参数是否取决于你。我想这会更容易分享搜索结果。