简体   繁体   English

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

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

design.php file: 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.php file: 并在index.php文件中使用此变量:

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

here while i am printing this variable it is getting zero can any one help 在这里,当我打印此变量时,它得到零可以任何帮助

you can't take var like this in php.. 您不能在php中使用这样的var。

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

because php is server side language .. 因为php服务器端语言 ..
and javascript is client side . javascript客户端

For this you have to use ajax ,get and post methods 为此,您必须使用ajax,get和post方法

the only solution I may know is using jquery on client side an sending your variable via ajax : 我可能知道的唯一解决方案是在客户端使用jquery通过ajax发送变量:

script.js script.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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM