Laravel Blade 在 php 中传递 Javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38224886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel blade pass Javascript variable in php
提问by utdev
How can I pass a javascript variable as an variable in my php loop:
如何在我的 php 循环中将 javascript 变量作为变量传递:
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:
此外,我尝试用 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.
我不知道如何继续,希望得到一些帮助。
回答by rdiz
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
PHP 甚至在页面访问您的浏览器之前就已经完成了它的工作,因此将变量从 Javascript 传递到 PHP 而不执行另一个请求是根本不可能的。考虑
A)Moving your loop to Javascript. Consider using some UI library like Vue.js, Angularor React.
A)将循环移动到 Javascript。考虑使用一些 UI 库,如Vue.js、Angular或React。
B)Move the contents of myJsVar
to PHP. If it depends on user input or browser rendering, that impossible.
B)将 的内容移动myJsVar
到 PHP。如果它取决于用户输入或浏览器呈现,那是不可能的。
C)Performing the rendering logic through an Ajax-request
C)通过 Ajax 请求执行渲染逻辑
$.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.
小心使用后一种方法 XSS-wise。
回答by omarjebari
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:
我使用刀片中的一个部分来添加 javascript,然后将其拉入布局中。下面的示例显示了模型的整数/字符串/集合的传递,例如:
// 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:
// 布局(javascript 可以在布局中的任何位置,即头部或主体:
<!DOCTYPE html>
<html>
<body>
@yield('content')
@yield('javascript')
</body>
</html>