简体   繁体   English

Ajax网址不起作用+ Symfony2

[英]Ajax url to action not working + Symfony2

I want to make an ajax call with jquery autocomplete like this: 我想用jquery autocomplete进行ajax调用,如下所示:

$("#register_player_team").autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "{{path('volley_scout_getteams_data')}}",
            dataType: "jsonp",
            success: function( data ) {
                console.log(data);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
    }
});

In my routing.yml I have the following route defined: 在我的routing.yml中,我定义了以下路由:

volley_scout_getteams_data:
pattern:  /team/getteams
defaults: { _controller: VolleyScoutBundle:Team:getteams }

And in my TeamController I have an action called getteamsAction(): 在我的TeamController中,我有一个名为getteamsAction()的动作:

public function getteamsAction()
{
    $entityManager = $this->getDoctrine()->getManager();
    // Get teams from database
    $teams = $entityManager->getRepository('VolleyScoutBundle:Teams')->findAll();

    foreach($teams as $team){
        var_dump($team);
    }

    die();
}

(The dump and die() is just for testing, I want to check if he can find the link). (dump和die()仅用于测试,我想检查他是否可以找到链接)。 But when I want to make the ajax call I always get the following error: 但是当我想进行ajax调用时,我总是会收到以下错误:

http://localhost:8080/volleyscout/web/app_dev.php/user/%7B%7Bpath('volley_s…)%7D%7D?callback=jQuery110207641139030456543_1389372448462&_=1389372448463 404 (Not Found) 

For some reason he can't find the action ... Does someone knows what I'm doing wrong? 由于某种原因,他无法找到行动......有人知道我做错了什么吗? And when I try the link like this: web/app_dev.php/team/getteams I get a dump of the teams .. 当我尝试这样的链接: web/app_dev.php/team/getteams我得到了团队的转储..

UPDATE: My javascript links are defined in base view (twig) like this: 更新:我的javascript链接在基本视图(twig)中定义如下:

{% block javascripts %}
    {% javascripts
        '@VolleyScoutBundle/Resources/public/js/jquery-1.10.2.min.js'
        '@VolleyScoutBundle/Resources/public/js/*'
    %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

And the ajax call is in my page.js: 而ajax调用在我的page.js中:

(function () {
    $("#register_userType").change(function(){
        var value = $(this).find("option:selected").val();
        if(value == 'P' || value == 'T'){
            $('.teams').show();
        }
        else{
            $('.teams').hide();
        }
    });
    $("#register_player_team").autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "{{path('volley_scout_getteams_data')}}",
                dataType: "jsonp",
                success: function( data ) {
                    console.log(data);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log(xhr.status);
                    console.log(thrownError);
                }
            });
        }
    });
})();

UPDATE 2: I did the following things: 更新2:我做了以下事情:

  • Installed the bundle 安装捆绑包
  • Added the bundle to my AppKernel 将捆绑包添加到我的AppKernel
  • Registered the routing definition in app/config/routing.yml 在app / config / routing.yml中注册了路由定义
  • Published assets (php app/console assets:install --symlink web) 发布的资产(php app / console assets:install --symlink web)

Added the 2 javascript lines to my base.html.twig like this: 将2条javascript行添加到我的base.html.twig,如下所示:

{% block javascripts %}
    {% javascripts
        '@VolleyScoutBundle/Resources/public/js/jquery-1.10.2.min.js'
        '@FOSJsRoutingBundle/Resources/public/js/router.js'
        '@VolleyScoutBundle/Resources/public/js/bootstrap.min.js'
        '@VolleyScoutBundle/Resources/public/js/jquery-ui-1.10.3.custom.min.js'
    %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    <script src="{{ path('fos_js_routing_js', {"callback": "fos.Router.setData"}) }}"></script>
    <script src="{{ asset('bundles/volleyscout/js/security.js') }}"></script>
{% endblock %}

But now I get this errors: 但现在我得到了这个错误:

GET http://localhost:8080/volleyscout/web/app_dev.php/js/routing?callback=fos.Router.setData 500 (Internal Server Error) register:117
Uncaught Error: The route "volley_scout_getteams_data" does not exist. 

It's very strange. 这很奇怪。 When I clear my cache, the first time it works perfectly. 当我清除缓存时,它第一次完美运行。 And when I refresh it shows the errors ... 当我刷新它显示错误...

The following line in your javascript code 您的javascript代码中的以下行

url: "{{path('volley_scout_getteams_data')}}",

won't work... 不会工作......

The best way is to use the FOSJsRoutingBundle 最好的方法是使用FOSJsRoutingBundle

1 Install FOSJsRoutingBundle to expose your routing in your JavaScript code. 1安装FOSJsRoutingBundle以在JavaScript代码中公开路由。 (very straight-forward) (非常直截了当)

2 Enable your route 2启用您的路线

volley_scout_getteams_data:
    pattern:  /team/getteams
    defaults: { _controller: VolleyScoutBundle:Team:getteams }
    options:
        expose: true

3 Adapt your js 3调整你的js

var getTeamsUrl = Routing.generate('volley_scout_getteams_data');

$("#register_player_team").autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: getTeamsUrl,
            //...
        });
    }
});

Came across this question/answer and almost started to install the mentioned FOSJsRoutingBundle mentioned by @Mick in the answer. 遇到这个问题/答案,几乎开始在答案中安装@Mick提到的提到的FOSJsRoutingBundle。 As I had the exact same problem in my Ajax Request I couldn't get the URL. 由于我在Ajax请求中遇到完全相同的问题,因此无法获取URL。 But now I don't see the need to get the FOSJsRoutingBundle.. 但是现在我没有看到需要获得FOSJsRoutingBundle ..

What is an input field without a <form> tag? 什么是没有<form>标记的输入字段? Or even better: why is my <input> field not in a <form> ? 或者甚至更好:为什么我的<input>字段不在<form> It is absolutely valid HTML to have <input> fields outside a form tag, but it actually makes no sense. 在表单标记之外使用<input>字段是完全有效的HTML,但实际上没有意义。

Anyway, it makes sense to have <form> arround the <input> so also if the javascript shouldn't work, why so ever, it would sent the request to the right place and load the page. 无论如何,让<form>围绕<input>是有意义的,所以如果javascript不起作用,为什么如此,它会将请求发送到正确的位置并加载页面。 So now if you have a form arround the input just grab the URL from there... 所以现在如果你有一个表单arround输入只是从那里抓取URL ...

This worked for me: 这对我有用:

Add a <form> 添加<form>

{{ form_start(form, {'action': path('volley_scout_getteams_data')}) }}

get the URL/path with javascript 用javascript获取URL /路径

$.ajax({
    url: $(this).closest('form').attr('action'),

从您的ajax网址中删除{{}}。

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

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