【问题标题】:Ajax with twig, how it works?带有树枝的 Ajax,它是如何工作的?
【发布时间】:2017-05-06 08:22:14
【问题描述】:

从我的控制器中,我在 html.twig 中发送了几个参数,然后我想发出一个像这样的 AJAX 请求:

{% if text is defined %}
    var text = {{ text }};
    var sender = {{ sender }};
    var date_send = {{ date_send|date('d/m/Y') }};
    var mess_type = {{ mess_type }};
    var to = {{ to }};

    $.post('send.php', {text:text, sender:sender, date_send:date_send, mess_type:mess_type, to:to}, function(data)
    {
        $('#Map').text(data);
    });
{% endif %}

所以当我这样做时,我有这个错误:

POST http://localhost:8000/send.php 500 (Internal Server Error)

我的 send.php 是我的 html.twig 所在的位置。我的 send.php 中只有一个 echo "hi" 用于测试,但它没有显示任何内容。

我还尝试在我的控制器中放置一个发送功能:

/**
* @Route("/send.php", name="send")
*/
public function send(Request $request) {
    dump("hi");
    echo "send";
    return null;
}

我将'send.php' 替换为{{path('send.php')}} 在我的html.twig 内(在$.post() 内)。 我知道我不能返回 null,但它不显示我的转储。我有这个错误:

An exception has been thrown during the rendering of a template ("Unable to generate a URL for the named route "/send" as such route does not exist.")

它并没有让我到达/send.php。我不知道我会错过什么,我在谷歌上没有找到任何解决方案。感谢您的帮助。

【问题讨论】:

  • path 方法中的参数应该是路由名称,所以在你的情况下应该是 send
  • 我也试过send,但我仍然有这个错误:jquery-1.11.3.js:9664 POST http://localhost:8000/send 500 (Internal Server Error)
  • 如果您收到 500 并且无法读取错误消息,请查看日志。在那里你应该找到答案。
  • 这个错误是我日志中的错误,但 symfony 没有显示任何错误

标签: javascript php jquery ajax symfony


【解决方案1】:

控制器的方法应该返回一个 Response 对象,所以试试这个:

/**
 * @Route("/send.php", name="send")
 */
public function send(Request $request)
{
    return new Response('send');
}

twig path 函数需要路由名称而不是路径,所以尝试以下操作:

{{path('send')}}

希望有帮助

注意:我为了识别真正的错误信息,尝试将 url 放入浏览器中看看会发生什么

【讨论】:

  • 它运作良好,谢谢,但是如何在我发送的发送函数中使用我的参数?我的转储(“hi”)没有显示任何内容
猜你喜欢
  • 2013-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-25
  • 1970-01-01
相关资源
最近更新 更多