Laravel blade pass Javascript variable in php

纵饮孤独 提交于 2020-04-13 17:08:29

问题


How can I pass a javascript variable as an variable in my php loop:

Something like this(obviously does not work):

        var myJsVar = 100;

        @for ($i = 0; $i<myJsVar; $i++)
            ... some code
        @endfor

Further I tried solving this with ajax:

        /**
         *  Get slider value
         */
        $.ajax({
            type: 'GET',
            url: myUrl,
            data: myJsVar,
            success: function (option) {
                console.log(myJsVar);
            }
        });

It returns me the success function,

Further I did this in my Controller:

public function prod(Request $request)
{
    if ($request->ajax()) {
        $ajax = "AJAX";
        dd($ajax);
    } else {
        $ajaxN = "NO Ajax";
        dd($ajaxN);
    }
}

It did not work.

I am not sure how to proceed, hope for some help.


回答1:


PHP has finished doing its work even before the page hits your browser, so passing a variable from Javascript to PHP without doing another request is simply impossible. Consider

A) Moving your loop to Javascript. Consider using some UI library like Vue.js, Angular or React.

B) Move the contents of myJsVar to PHP. If it depends on user input or browser rendering, that impossible.

C) Performing the rendering logic through an Ajax-request

$.ajax({
            type: 'GET',
            url: myUrl,
            headers: {'X-Requested-With': 'XMLHttpRequest'},
            data: {value: myJsVar},
            success: function (response) {
                $(someContainer).html(response);
            }
        });

And in your controller:

public function prod()
{
   $value =  Request::get('value');

   return view('view-with-a-loop')->with('value', $value);
}

Be careful with the latter method XSS-wise.




回答2:


I use a section in blade to add the javascript then pull that into the layout. The example below shows passing of integer/string/collection of models, eg:

// blade template

@extends('layouts.app')

@section('javascript')

<script type="text/javascript">
    var myInteger = {!! $myInteger !!};
    var myString = '{!! $myInteger !!}';
    var myObject = {!! json_encode($models) !!};
</script>

@endsection

@section('content')
...
@endsection

// Layout (the javascript can go anywhere in the layout, ie the head or body:

<!DOCTYPE html>
<html>
<body>
    @yield('content')
    @yield('javascript')
</body>
</html>


来源:https://stackoverflow.com/questions/38224886/laravel-blade-pass-javascript-variable-in-php

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