Use js function variable in route

ⅰ亾dé卋堺 提交于 2019-12-12 01:46:19

问题


I want to pass ID to my route via ajax but cant do that:

function test(id){
   $('#items').DataTable({
      ajax: {
      url: '{!!  route('routename', ['menu_id' => id]) !!}',
          type: 'POST'
      },

It says Use of undefined constant id. How can i use javascript variables to pass through route?


回答1:


It is not possible to use javascript variables in PHP as server side code is executed before client side code. So you may assign JS variables to equal PHP variables but not the other way around. Check this out: https://stackoverflow.com/a/2379251/7377984

You have the following options:

  1. Instead of route parameters, you may use request parameters
  2. If you really want to use route parameters, you would have to store your routes in your JS code (e.g. if the route is http://www.example.com/routename/{menu_id}, you may store the route variable as an absolute url like so: var route = http://www.example.com/routename/ or as a relative url like so: var route = /routename/ and then in the ajax request append the route parameter like so url: route + id



回答2:


You Can try this.

$(document).on('click', '.clickClass', function () {

            var id=$(this).val();
            var action = "{{ URL::to('yourroutehere') }}/"+id;

            $(".hreflink").attr('href',action);
});

<a href="" class="hreflink">Action</a>



回答3:


I think you can do this :

function test(id){
   var Link = "{!! route('routename',['menu_id' => '']) !!}"+"/"+id;
   $('#items').DataTable({
      ajax: {
      url: Link,
      type: 'POST'
},


来源:https://stackoverflow.com/questions/42042682/use-js-function-variable-in-route

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