Print JavaScript variable value inside a php tag using blade template in Laravel

北慕城南 提交于 2019-12-07 09:30:43

问题


Suppose this is a JS code and I want to print the value of id . Here id is a variable with a value receiving into the jq function.

function follow_or_unfollow(id,action){         
     myUrl = "{{ action('FollowsController@show', 'id') }}" ;               
}

If we mension 'id' it will show the id string.

PS. here {{ is using as it meant as php code in blade template.

Now i need to print the script variable inside a php code.


回答1:


I am afraid that what you are asking is not possible. The simple reason being JavaScript is client-side and PHP is server-side.

You can always place PHP code inside JavaScript because it will just be echoed there and won't run at that very instant. Whereas if you want to use a JavaScript variable inside PHP, that means you are trying to access a variable which doesn't even exist at the point of when the server processes the request.

Update

There is a workaround to this. You can pass the data which is needed in JS as parameters in the URL and then get these values in PHP using $_GET.




回答2:


Probably its late, but I think I have solution. Your code

myUrl = "{{ action('FollowsController@show', 'id') }}" ;

is inside javascript block. Therefore the blade parser use parenthesis as javascript object rather as blade variable. So you can't use any PHP variables inside script block. In my solution I would replace your line with:

myUrl = "@include("public.default.js_values.myUrl")" ;

and then create that template file

(in your views folder)/public/default/js_values/myUrl.blade.php

and add one line into that file

{{ action('FollowsController@show', 'id') }}

This way blade parser will include the content on myUrl.blade.php. In file will correctly resolve that in parenthesis is variable and returns the value of php variable (in your case the method) back to javascript.

I have tested this in similar situation and it worked.




回答3:


Just use {!! $vars !!}.

var link = {!! "'".url('string/'.$vars.'/string')."'" !!};


来源:https://stackoverflow.com/questions/20177054/print-javascript-variable-value-inside-a-php-tag-using-blade-template-in-laravel

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