传递了一个JavaScript数组PHP变量在同一个PHP文件数组、变量、文件、在同一个

2023-09-10 18:33:06 作者:风雨兼程

我有这个PHP文件,其中我需要这个JavaScript变量可用(在同一个文件)是通过对我的PHP变量,这样的事情。

myfile.php contais:

  VAR测试= [EWMLMc3ES3I,RSdKmX2BH7o,SIXwlxhjaKY,acp8TbBPVos,6GpKR4-TLoI,XLKLkTnKRwg,6WPELkw5kD0];
 

和我想让它像这样

 测试=<?PHP $ new_testing>
 

我需要一个建议也许是jQuery的片段,但喜欢的东西我的方案是在一个PHP文件中的JavaScript。

编辑:更多的信息,这样做的原因是,因为有另一个JavaScript codeS(不在同一个文件,而是有它通过外部JS包括)需要特定的PHP变量。 所以说,这里的逻辑:

javascript_variable ---> php_variable(通过JavaScript变量到PHP),那么, php_variable - > another_javascript_variable(PHP的传递给另一个JavaScript文件) 的another_javascript_variable将被外部JavaScript文件执行 解决方案 JavaScript数组常见用法

在你的PHP端,使用的 json_en code()到你的php数组转换成合适的格式将它传递给JavaScript。

PHP:

  $ VAR =阵列(LOREM,存有,悲);
$ json_var = json_en code($ VAR);
$参数=阵列('js_var'=> $ json_var);
wp_enqueue_script('my_script');
wp_localize_script('my_script','OBJECT_NAME',$参数);
 

Javscript:

 <脚本>
my_var = jQuery.parseJSON(object_name.js_var);
警报(my_var);
< / SCRIPT>
 

I have this PHP file wherein I need this javascript variable available (inside the same file) to be pass on my PHP variable, something like this.

myfile.php contais:

    var testing  = ["EWMLMc3ES3I", "RSdKmX2BH7o", "SIXwlxhjaKY", "acp8TbBPVos", "6GpKR4-TLoI", "XLKLkTnKRwg", "6WPELkw5kD0"];

and I want to make it like this

 testing = <?php $new_testing ?>

I need a suggestion maybe a jquery snippet but with something like my scenario which is a javascript in a php file.

edit: additional info, the reason for this is , because there's another javascript codes (not on the same file but rather had it include via external JS) that needs that particular PHP variable. so say here's the logic:

javascript_variable ---> php_variable (passing the javascript variable to php) then, php_variable --> another_javascript_variable (pass the php to another javascript file) the another_javascript_variable will the be executed by that external javascript file

解决方案

On your PHP side, use json_encode() to convert your php array to a suitable format to pass it to the javascript.

PHP:

$var = array( 'lorem', 'ipsum', 'dolor');
$json_var = json_encode($var);
$parameter = array( 'js_var' => $json_var );
wp_enqueue_script('my_script');
wp_localize_script('my_script', 'object_name', $parameter); 

Javscript:

<script>
my_var = jQuery.parseJSON(object_name.js_var);
alert(my_var); 
</script>

 
精彩推荐
图片推荐