如何使用 javascript 值设置 php 变量并在外部 php 文件中使用该 php 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14376657/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:09:33  来源:igfitidea点击:

how to set the php variable with javascript value and use that php variable in external php file

php

提问by subhash

design.phpfile:

design.php文件:

 <script>
    $(".colr_sldr li img").click(function(){
    var src = $(this).attr('src');
    var value=src.substring(src.lastIndexOf('/')+1);
    <?php $var = "<script>document.write('" + value + "')</script>";?>
     });
    </script>

and use this variable in index.phpfile:

并在index.php文件中使用此变量:

<?php 
include('design.php');
echo $var;
?>

here while i am printing this variable it is getting zero can any one help

在这里,当我打印此变量时,它变为零,任何人都可以提供帮助

回答by sourcecode

you can't take var like this in php..

你不能在 php 中使用这样的 var ..

$var = "<script>document.write('" + value + "')</script>";?>

because phpis server side language..
and javascriptis client side.

For this you have to use ajax ,get and post methods

因为php服务器端语言..
javascript客户端

为此,您必须使用ajax 、get 和 post 方法

回答by Vitalii Strimbanu

the only solution I may know is using jquery on client side an sending your variable via ajax :

我可能知道的唯一解决方案是在客户端使用 jquery 并通过 ajax 发送您的变量:

script.js

脚本.js

$('document).ready(function(){
       var myVar="Hello";
      $.post('design.php',myVar);

});

and in design.php you have acces to your variable with $_POST design.php

在 design.php 中,您可以使用 $_POST design.php 访问变量

<?php 
   $myVar = $_POST['myVar'];
   echo $myVar;?>

please check http://api.jquery.com/jQuery.ajax/for more details

请查看http://api.jquery.com/jQuery.ajax/了解更多详情

or http://api.jquery.com/jQuery.post/

http://api.jquery.com/jQuery.post/