Laravel 4, Pass a variable to route in javascript

*爱你&永不变心* 提交于 2019-12-17 10:54:27

问题


How Can I pass the variable (stock.id) return from Ajax response to the route to generate the url to edit a stock

$.ajax({
            url: 'sectors/stocks/' + $(this).data('sector-id'),
            dataType:'json',
            beforeSend:function() {
                $('.stocks_list').html('Loading...');
            }
        })
        .done(function(data) {
            $('.stocks_list').html('<ul>');
            $.each(data, function(index, obj_data) {
                $.each(obj_data.stocks, function(indx, stock) {
                    $('.stocks_list').append('<li><a href="{{route("admin.stocks.edit","'+stock.id+'")}}">' + stock.symbol + ' </a></li>');     
                });
        });
    })

回答1:


You can first use a placeholder to generate the URL with and then replace that in javascript.

var url = '{{ route("admin.stocks.edit", ":id") }}';
url = url.replace(':id', stock.id);
$('.stocks_list').append('<li><a href="'+url+'">' + stock.symbol + ' </a></li>');



回答2:


Thanks lukasgeiter, you make my day. It works. Only must to change the replace method because laravel scape ":" to "%3A"

var url = '{{ url("/admin/solicitud", ":id") }}';
url = url.replace('%3Aid', data.datos[i].id);
dhtml+='<td><a href="'+url+'" class="btn btn-primary" role="button">Ver más...</a></td>';   

or simple let the id string only

var url = '{{ url("/admin/solicitud", "id") }}';
url = url.replace('id', data.datos[i].id);
dhtml+='<td><a href="'+url+'" class="btn btn-primary" role="button">Ver más...</a></td>';



回答3:


Best way to use route in ajax.


Add route in hidden input or take as a attribute into the button or link. Like below.

This will save the other jquery code like get id and pass into the url. It's simple just get the url from input and pass as a URL. That's it.

<a data-url="{{ route('delete.PendingPatient',['id' => $u->id]) }}" class="btn btn-xs btn-danger btn_delete"> Delete </a>

Route

<?php

Route::delete('/pending_patient/{id}','PatientController@pending_patient'])->name('delete.PendingPatient');

jQuery

    <script type="text/javascript">
        jQuery(document).ready(function(){

          jQuery(document).on('click','.btn_delete',function(){
             var current = jQuery(this);
             var url = current.data('url');

             $.ajax({
                    url: url,
                    dataType:'json',
                    beforeSend:function() {
                        $('.stocks_list').html('Loading...');
                    }
                })
                .done(function(data) {
                    $('.stocks_list').html('<ul>');
                });

              });

         });
     });
</script>


来源:https://stackoverflow.com/questions/27634285/laravel-4-pass-a-variable-to-route-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!