简体   繁体   中英

Symfony2 - Issue getting correct id to show/{id}

I have a view page which is passed all my active alerts. On each displayed row, I have a show button so you can see the individual alert

{% for alert in alerts %}
    <tr>
        <td>{{ alert[0].id }}</td>
        <td>{{ alert[0].alertStatus }}</td>
        <td>
            <input type="button" value="Show" data-url="{{ path('NickAlertBundle_show', {id: alert[0].id}) }}" onclick="show_alert( {{ alert[0].id }} )" id="show"/>
        </td>
    </tr>
{% endfor %}

So when the button is clicked, the javascript function show_alert is called.

function show_alert(id){
    alert(id);
    $.ajax({
        type: "POST",
        url: $("#show").attr('data-url'),
        data: {id: id},
        success: function(data) {
            if(data){

            }else{
                alert("Unknown Error!");
            }
        },
        error:function(){
            alert(id);
        }
    });
}

Now I do an alert at the top of that function, and that alert always displays the correct id. I think the problem is with the url part of the ajax call. It calls the data-url which should be correct. This is what it should be calling

NickAlertBundle_show:
    pattern:  /show-alert/{id}
    defaults: { _controller: NickAlertBundle:Alert:show }
    requirements:
       _method:  GET|POST
       id:  \d+

So this should then call the controller action

public function showAction(Request $request, $id)
{
    var_dump($id);
    if($request->isXmlHttpRequest())
    {
        $id = (int)$request->request->get('id');
    }

    return new JsonResponse('test');
}

At this point though, the var_dump in this action always outputs the id of the last added alert, and not the selected alert. And when I display the alert, it always displays the latest added alert.

So what is causing it to get the latest alert id instead of the selected id? As I say, it initially gets the correct id, but at some point this changes.

Thanks

你不应该在你的模板中声明重复的id,比如id =“show”,更好地使用class或声明你的id,比如id="show_1 ... n"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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