简体   繁体   English

如何将JavaScript变量分配给PHP变量?

[英]How do I assign a javascript variable to a PHP variable?

I have a javascript variable which holds some information and I want that to assign in a PHP variable. 我有一个包含一些信息的javascript变量,我希望将其分配给PHP变量。 Here is what I am using: 这是我正在使用的:

<script type="text/javascript">
function redirectToFacebook()
{
    var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>

<?php
    $_SESSION['sess_facebook_message'] = facebookMessage;
?>

Any help is really appriciable. 任何帮助都是切实可行的。

Thanks in advance 提前致谢

Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent. 由于PHP在服务器上运行,而JavaScript在客户端上运行,因此无法在使用JavaScript后设置PHP会话变量,因为PHP甚至在发送页面之前就已经执行完了。

However... 然而...

If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can. 如果使用JavaScript向设置该变量的PHP脚本发出请求(AJAX,imagehack或其他方式),则可以。

For example... 例如...

JavaScript: JavaScript:

function something() {
    // do something with somevar
    somevar = 'content';
    // make an AJAX request to setvar.php?value=content
}

PHP: PHP:

$_SESSION['somevar'] = $_GET['somevar'];

Make sure you take security issues of client-generated data into account, though. 但是,请确保考虑到客户端生成的数据的安全性问题。

If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either: 如果要将变量从浏览器(javascript)传递到后端服务器(PHP),则需要执行以下任一操作:

1) Load a new page with Javascript parameters encoded either as POST or GET 2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET 1)加载带有编码为POST或GET的Javascript参数的新页面2)异步调用将参数编码为POST或GET的PHP脚本(AJAX调用)

A simple example using a GET request (you simply append your parameters to the URL): 一个使用GET请求的简单示例(您只需将参数附加到URL):

<script>
    window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>

You probably want to assign this piece of code to a button or something... 您可能希望将这段代码分配给按钮或其他东西。

由于API的限制,您试图实现的目标是不可能的。

may be you can try to redirect with javascript and pass variables form php to js. 可能是您可以尝试使用javascript重定向并将变量形式从php传递给js。 They way yout tru it, it can't work. 他们以自己的方式来操纵它,这是行不通的。

may be, im realy not shure try this. 可能是,我真的不敢尝试这个。

<?php
function redirectToFacebook() { 

var facebookMessage = ?>
<script>
    document.write(encodeURI(document.getElementById('txt_msg').value)); 
</script>
<?php
}
?>

or using cookies. 或使用Cookie。

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

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