将 Javascript 变量转换为 PHP 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8859401/
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
Converting Javascript variable to a PHP variable
提问by AJ Naidas
I would like to use a javascript variable that was returned to me by a videoel.getCurrentTime function and convert it to a php variable for me to able to add it up to my SQL Insert Query like INSERT INTO tblData VALUES ('$phpVarFromJavascript');
我想使用 videoel.getCurrentTime 函数返回给我的 javascript 变量,并将其转换为 php 变量,以便我能够将其添加到我的 SQL 插入查询中,例如 INSERT INTO tblData VALUES ('$phpVarFromJavascript') ;
回答by Aidanc
You don't "convert" it. Send it using a get request or something similar to the php page.
你不会“转换”它。使用 get 请求或类似于 php 页面的内容发送它。
Javascript runs on the client side while php runs on the server side.
Javascript 在客户端运行,而 php 在服务器端运行。
There are many different ways you can do this and which one you choose depends on your particular situation. However, I think it's important to check how this all works and for you to make sure you understand the difference between client side and server side.
有许多不同的方法可以做到这一点,您选择哪一种取决于您的具体情况。但是,我认为重要的是检查这一切是如何工作的,并确保您了解客户端和服务器端之间的区别。
Check w3c's example. The Javascript part makes a request to the php file when the user chooses a person. The php file then queries the MySQL database and responds to the Javascript file which then in turns presents the result to the user.
检查w3c 的示例。当用户选择一个人时,Javascript 部分会向 php 文件发出请求。php 文件然后查询 MySQL 数据库并响应 Javascript 文件,然后将结果呈现给用户。
The particular code used in this example I would not recommend using in production. The MySQL database information is stored in plain text which anyonecould read. I'm using this link purely as a working example of how everything works together.
本示例中使用的特定代码我不建议在生产中使用。MySQL 数据库信息以任何人都可以阅读的纯文本形式存储。我将此链接纯粹用作说明一切如何协同工作的工作示例。
回答by LoveAndCoding
JavaScript cannot interact with PHP unless it is via an AJAX request. What you would need to do is send it via AJAX to the page, and then use PHP to access the variable.
JavaScript 不能与 PHP 交互,除非它是通过AJAX 请求。您需要做的是通过 AJAX 将其发送到页面,然后使用PHP 访问变量。
回答by Sudarshan G Hegde
This will convert js variable to php variable and php variable to js variable
这会将 js 变量转换为 php 变量,将 php 变量转换为 js 变量
<script>
function jstophp(){
var javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar;?>";
}
function phptojs(){
var javavar2 = "<?php
$phpvar2="I am php variable value";
echo $phpvar2;
?>";
alert(javavar2);
}
</script>
<body>
<div id="rslt">
</div>
<input type="text" id="text" />
<button onClick="jstophp()" >Convert js to php</button>
<button onClick="phptojs()">Convert php to js</button>
PHP variable will appear here:
<div id="rslt2">
</div>
</body>