在Twig的AJAX调用中找不到PHP文件 [英] PHP file not found in AJAX call in Twig

查看:53
本文介绍了在Twig的AJAX调用中找不到PHP文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Symfony 2.8练习AJAX调用的单元测试.

I am practicing unit test for AJAX call in Symfony 2.8.

这是我的代码:

<script>
QUnit.test("test dynamic fill", function (assert) {
            var ajax = $("#ajax"); //my div to fill
            $("#feed_the_ajax").click(function () {
                $.ajax({
                    url: "echo.php",
                    type: "POST",
                    data: {text: "Hello world !"},
                    success: function (data) {
                        ajax.text(data);
                    },
                    error: function () {
                    }
                });
                assert.ok(!ajax.text() == "Hello world !", "Hello !");
            });
            assert.ok(!ajax.text() == "Hello world !", "Answer me ...");
        });
</script>

它位于树枝文件中.

echo.php文件就是这样:

echo.php file is just like this :

<?php
if($_POST['text'] != ""){
    return $_POST['text'];
}

运行代码时,它告诉我找不到"echo.php".

When I run the code, it tells me that "echo.php" is not found.

所以有两个问题:

1)首先,我是否应该像这样(在树枝中)调用AJAX,还是应该使用Controller?

1) First, am I doing it wright to call an AJAX like this (in the twig) or should I use the Controller ?

2)其次,应该将我的PHP文件放在哪里以避免404错误?

2) Secondly, where should I put my PHP file to avoid 404 error ?

感谢您的回答,Telest

Thanks for your answers, Telest

修改16年8月7日

问候,

我将与您分享我的解决方案.我只使用了一个名为FOSJsRoutingBundle的捆绑包,该捆绑包将生成到控制器中函数的路由.然后,我将"echo.php"转换"为带有控制器中路由的函数,回答了"Response"(响应),然后……Tadaa!

I am back to share with you my solution. I simply use a bundle called FOSJsRoutingBundle, that will generate a route to a function in the controller. Then I "convert" my "echo.php" into a function with a route in my controller, answered a Response and ... Tadaa !

解决了!

感谢您的帮助!问候

推荐答案

1)

您不能将JS放入Controller.

You can't put JS in the Controller.

但是您可以将其保存在javascript文件中(位于app/Ressources/public/js/MyJSfile.js中)

But you can save it in a javascript file (located at app/Ressources/public/js/MyJSfile.js)

并使用:

{% javascripts 'js/MyJSfile.js' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}

(请参阅此处: http://symfony.com/doc/current/best_practices/web-assets.html )

2)

您的echo.php应该在web文件夹中.(但是您的服务器配置需要允许它,基本上在安装symfony时,会将所有请求重定向到app.php或app_dev.php).

Your echo.php should be in the web folder. (but your server configuration needs to permit it, basically when you install symfony, you redirect all requests to app.php or app_dev.php).

这篇关于在Twig的AJAX调用中找不到PHP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆