如何在 PHP 中使用 javascript 变量

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

How to use javascript variables in PHP

phpjavascript

提问by Kode Plus

Possible Duplicate:
How can I use a JavaScript variable as a PHP variable?

可能的重复:
如何将 JavaScript 变量用作 PHP 变量?

I need to use javascipt variables in PHP, how can I do that?

我需要在 PHP 中使用 javascipt 变量,我该怎么做?

eg:

例如:

<script>
var abc = 'this is text';
</script>

How can I read variable abcin php?

如何abc在php中读取变量?

回答by Conrad Lotz

One way of doing it is to make use of a hidden text/input box.

一种方法是使用隐藏的文本/输入框。

<input type="text" style="display:none" id="hiddenVal" />

In the Javascript assign the variable to the input box.

在 Javascript 中将变量分配给输入框。

<script>
function loadValues()
{
var abc = 'this is text';
document.getElementById("hiddenVal").value = abc;
//alert(document.getElementById("hiddenVal").value);
}
</script>

<body onload="loadValues();">

<form action="processing.php" method="post">
  <input type="text" style="display:none" id="hiddenVal" />
  <input type="submit" name="submit" id="submit" value="Submit" />
</form>
</body>

This is one method to allow you to use Javascript variable and post it to the backend. Alternatively if you want to display these values just remove the

这是一种允许您使用 Javascript 变量并将其发布到后端的方法。或者,如果您想显示这些值,只需删除

style="display:none"

风格=“显示:无”

on the control.

在控件上。

Now after the post occurred one should be able to pick up the variable using processing.php

现在帖子发生后,应该能够使用processing.php获取变量

<?php
echo $_POST["hiddenVal"];
?>

Very dirty way of doing this but does the trick.

这样做的方式非常肮脏,但可以解决问题。

回答by Pradeeshnarayan

I am not sure will this help you in anyway. But in this way you can use javascript in server side.

我不确定这是否会对您有所帮助。但是通过这种方式,您可以在服务器端使用 javascript。

<script type="text/javascript">
var abc= 'this is text';
<?php $abc = "<script>document.write(abc)</script>"?>   
</script>
<?php echo $abc;?>

回答by jeremy

You're going to want to try something with AJAX. jQuery has a nice AJAX libraryif doing it pure doesn't sound too appealing to you.

您将想尝试使用 AJAX 进行一些操作。jQuery 有一个很好的AJAX 库,如果它纯粹地听起来对你来说不太吸引人的话。

回答by amitchhajer

The way its possible is:

它可能的方式是:

redirect to a php script

重定向到一个 php 脚本

or

或者

an AJAX call to a PHP script

对 PHP 脚本的 AJAX 调用