简体   繁体   English

使用 javascript 在输入中获取 php 变量的值

[英]get the value of a php variable in an input using javascript

I want to concatenate the value of my variable $variable with the value of my input using javascirpt我想使用 javascirpt 将我的变量 $variable 的值与我的输入值连接起来

$variable= file_get_contents('./env.txt');

<select id="customer_id" name="customer_id" w300 required pj-chosen" data-msg-required="<?php __('lblFieldRequired');?>" onchange="document.getElementById('title').value=this.value + 'P' + **$variable**">
...
                    <input type="text" name="title" id="title" class="pj-form-field w400 required" data-msg-required="<?php __('lblFieldRequired');?>" data-msg-remote="<?php __('lblTitleUsed');?>"  value=""><script></script>

Ok so why not echo out the variable?好的,为什么不显变量呢?

PHP: PHP:

onchange="document.getElementById('title').value=this.value + 'P' + '<?php echo addslashes($variable) ?>'">

The addslashes call will escape quotes against security problems. addlashes调用将针对安全问题转义引号。

If $variable does not change a more elegant way is to make the $variable a JavaScript variable and then use it normally.如果$variable没有改变,更优雅的方法是将$variable设为 JavaScript 变量,然后正常使用。 This makes the JavaScript part more readable, but of course other programmers will have to be aware that you add that variable via PHP.这使得 JavaScript 部分更具可读性,但当然其他程序员必须知道您通过 PHP 添加该变量。

PHP: PHP:

// somewhere at the beginning of your body tag:
<script>
  window.variable = '<?php echo addslashes($variable) ?>';
</script>

HTML: HTML:

<... onchange="document.getElementById('title').value=this.value + 'P' + window.variable" />

I wrote this off the top of my head - please tell if this worked as I intended.我在脑海中写下了这个——请告诉我这是否符合我的预期。

On the line below you've already got some PHP inline in the HTML, outputting values into those data attributes.在下面的行中,您已经在 HTML 中内联了一些 PHP,将值输出到这些数据属性中。

For $variable you can follow much the same pattern as that, except you'll need to explicitly echo the variable so it gets embedded into the JavaScript (I assume those other functions echo within them, removing the need for another one):对于$variable ,您可以遵循与此大致相同的模式,除了您需要显式地回显变量,以便将其嵌入到 JavaScript 中(我假设其他函数在其中回显,不再需要另一个):

onchange="document.getElementById('title').value=this.value + 'P' + '<?php echo addslashes($variable); ?>'"

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

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