laravel 4: URL::route vs jquery

2019-02-10 16:53发布

(As new laravel user) I'm trying to build a ajax call url through the laravel URL::class:

$.ajax( {
    url: '{{ URL::route('getUser', ['3']) }}', 
    success: function(results) {
    alert(results);
    }
});

routes.php:

Route::get('admin/getUser/{user_id}', array(
   'as' => 'getUser', 
   'uses' => 'AdminController@getUser'
));

Instead of the hard coded 3 this parameter should come from jquery (e.g. $(this).attr('user_id')).

Can someone tell me how to create the URL dynamically?

It seems that because of the route definition the URL::route function needs the parameter hardcoded or as a php varaible.

I hope this is +/- clear...

Thanks for help anyway!

3条回答
你好瞎i
2楼-- · 2019-02-10 17:36

You could keep the url clean and pass the variable as data in your ajax call.

var urlGetUser = "{{ URL::route('getUser') }}",
    userId = $(this).attr('user_id');

$.ajax({
  type: "POST",
  url: urlGetUser,
  data: { id: userId }
}).done(function( msg ) {
  alert( msg );
});

This way you won't have to create ajax calls for every possible user ID. Something both other current solutions also offer.

Disclaimer: Colleague of asker with absolutely no experience in Laravel :/

查看更多
姐就是有狂的资本
3楼-- · 2019-02-10 17:36

I've been using URL::to() for my Ajax calls. I've had problems to. But if you do use URL::to() you would be able to use javascript variables. try this:

$id = 3;
"{{URL::to('getUser/'".$id.")}}"

Hope this helps, I'm new too. if you find a better way to do this awesome, let me know ;)

查看更多
小情绪 Triste *
4楼-- · 2019-02-10 17:54

Because PHP actually handles the file before passing it to the browser it may be indeed impossible to dynamically use a php variable directly, but theres a way around it. This may work ONLY if you havent type-casted your route parameter user_id to a certain definition.

// Add a placeholder which we'll use jQuery to swap out later
urlTo = "{{ URL::route('getUser', ['%userid%']) }}";

// swap out the placeholder dynamically using jQuery
urlTo = urlTo.replace('%userid%', $('#someElement').attr('user_id'));

$.ajax({
    url: urlTo, 
    success: function(results) {
        alert(results);
    }
});

What we've done here is to create a placeholder in our URL generated from a route so we'll probably have a URL like http://localhost/app/profile/%userid% after PHP has finished processing. We then use jQuery to replace the placeholder to our actual dynamic value.

查看更多
登录 后发表回答