【问题标题】:How to properly use AJAX in Symfony2如何在 Symfony2 中正确使用 AJAX
【发布时间】:2017-06-09 08:45:18
【问题描述】:

单击按钮后,我正在尝试使用 AJAX 运行我的控制器代码。根据我收集到的信息,这就是您应该使用 AJAX 的目的……它从前端向后端发送响应,然后生成 json 响应。

但是我不知道如何正确地做到这一点。我不确定如何让 AJAX 成功运行控制器代码。

我所能做的就是在成功时显示表格,但我不希望控制器代码在单击按钮之前运行,因为这是 AJAX 的重点。

Symfony 似乎没有这方面的文档:http://symfony.com/legacy/doc/book/1_0/en/11-Ajax-Integration

这些堆栈溢出问题/答案对我来说太旧了,或者对我没有帮助:

How to integrate Ajax with Symfony2

How to make a POST Ajax request with Symfony and Jquery

树枝:

<button id="begin-check" type="button">Run Test</button>

<table class="stab">
  <thead>
    <tr>
      <th style="text-align: center">Ang</th>
      <th style="text-align: center">Lat</th>
    </tr>
    <tr>
        <th>Name &amp; Age</th>
        <th>Name &amp; Age</th>
    </tr>
  </thead>
  <tbody>
  {% for person in persons %}
        <tr>
            <td>
                <a href="{{ path('users_edit', { 'id': person[0] }) }}">
                    {{ person[1] }}, {{ person[2] }} 
                </a>
            </td>
            <td>
            {% if person[7] == 'Moe' %}
                <a href="{{ path('edit', { 'id': person[6] }) }}">
            {% else %}
                <a href="{{ path('low_edit', { 'id': person[8] }) }}">
            {% endif %}
                    {{ person[4] }}, {{ person[5] }} 
                </a>
            </td>
        </tr>
    {% endfor %}
  </tbody>
</table>

AJAX:

<script type="text/javascript">
    $(document).ready(function(){
        $(document).on('click', "#begin-check", function(e){
            console.log('You have clicked');
            e.preventDefault();
            $.ajax({
                method: 'POST',
                url: "{{ path('control_check') }}",
                data: { //research what to put here
                 },
                success: function(responseData){
                    //run the controller code
                    //Show HTML table
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(xhr.responseText);
                    console.log(thrownError);
                },
            })
        });
    });

</script>

在控制器中:

/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction()
{
    $request = $this->get('request');
    $em = $this->getDoctrine()->getManager();

    $persons = array();

    //more code

    return new JsonResponse(array('persons' => $persons));

}

【问题讨论】:

  • 你的 javascript 代码是在 twig 模板中吗?
  • 它和我上面的树枝在同一个文件中
  • 您不能从您的 javascript 成功函数内部运行服务器端控制器代码。调用成功时,您的 responseData 将具有 controlCheckAction 生成的任何 json。然后,您需要 javascript 来呈现表格。看看你是否能找到一个很好的 ajax 入门教程,而不用 Symfony 的复杂性。您需要先了解基础知识。

标签: javascript php jquery ajax symfony


【解决方案1】:

我认为你需要添加到你已经拥有的只是isXmlHttpRequest() 方法。 Here是官方文档。

所以:

/**
 *
 * @Route("/control", name="control_check")
 * @Template()
 */
public function controlCheckAction(Request $request)
{
    if ($request->isXmlHttpRequest()) {
        //$request = $this->get('request');
        //replace the up line code with the folloging, which gets a particular form field
        $name = $request->request->get('name'); // <=> $name = $_POST['name']
        $em = $this->getDoctrine()->getManager();

        $persons = array();

        //more code

        return new JsonResponse(array('persons' => $persons));
    }
}

【讨论】:

  • 我肯定忘记将 Request $request 参数添加到控制器函数中......所以谢谢你,但我对 $request-&gt;request-&gt;get('name'); 对我来说是什么感到困惑。我这里没有要使用的表单域...
  • 然后只需在controlCheckAction() 中的dump($request) 就可以在按下提交按钮后查看可用的内容。我真的不知道你打算达到什么目的。通常在模板中存在一个&lt;form&gt;,它通过该 AJAX 调用发送其数据。
【解决方案2】:

大概,我也遇到过同样的情况。

就我而言,我忘记添加“使用”语句。 你不会忘记添加这一行吗?

use Symfony\Component\HttpFoundation\JsonResponse;

我附上我的检查点。

【1】查看服务器端应用日志

error_log("create json response OK" . "\n", 3, "/usr/local/var/log/php/error.log");
return new JsonResponse(array('persons' => $persons));

【2】检查控制台调试器

打开 chrome 调试器(F12) -> 网络选项卡 -> “/control”(左侧导航)

所以,你可以确认“响应头”。

[OK] Content-Type:application/json
[NG] Content-Type:text/html

如果你找到“text/html”,我认为是服务器端的问题。

【3】检查symfony2调试器

您可以在同一个标​​签页中找到 symfony2 调试器 url 【2】

X-Debug-Token-Link:http://xxxxxxxxx/_profiler/xxxxx

您应该打开此分析器链接。 如果这个问题来自服务器端,你可以找到任何问题。

【讨论】:

    猜你喜欢
    • 2013-07-05
    • 2016-07-22
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2011-12-22
    • 2011-07-06
    • 2021-04-19
    相关资源
    最近更新 更多