Print JavaScript variable value inside a php tag u

2019-05-07 05:00发布

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.

3条回答
仙女界的扛把子
2楼-- · 2019-05-07 05:34

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.

查看更多
我命由我不由天
3楼-- · 2019-05-07 05:41

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.

查看更多
爷的心禁止访问
4楼-- · 2019-05-07 05:42

Just use {!! $vars !!}.

var link = {!! "'".url('string/'.$vars.'/string')."'" !!};
查看更多
登录 后发表回答