Laravel刀片在PHP中传递Javascript变量 [英] Laravel blade pass Javascript variable in php

查看:93
本文介绍了Laravel刀片在PHP中传递Javascript变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在我的php循环中将javascript变量作为变量传递:

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

我还尝试使用Ajax解决此问题:

Further I tried solving this with ajax:

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

它向我返回成功函数,

我进一步在控制器中做到了

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);
    }
}

它不起作用.

我不确定该如何进行,希望有所帮助.

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

推荐答案

PHP甚至在页面访问您的浏览器之前就已经完成了其工作,因此根本无法将变量从Javascript传递给PHP.考虑

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).将循环移动到Javascript.考虑使用一些UI库,例如 Vue.js 角度反应.

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

B) myJsVar 的内容移动到PHP.如果它取决于用户输入或浏览器渲染,那是不可能的.

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

C)通过Ajax请求执行渲染逻辑

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);
            }
        });

在您的控制器中:

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

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

请谨慎使用XSS方式的后一种方法.

Be careful with the latter method XSS-wise.

这篇关于Laravel刀片在PHP中传递Javascript变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆