简体   繁体   English

将JavaScript变量传递给PHP Session变量

[英]Passing JavaScript Variable to PHP Session variable

I am trying to update/create session variable when I change the option thru a drop-down box. 当我通过下拉框更改选项时,我尝试更新/创建会话变量。 TThe value is stored in a javascript function. T该值存储在javascript函数中。 Can any1 tell me how I can pass this variable to my PHP session variable without using a AJAX request. any1可以告诉我如何在不使用AJAX请求的情况下将此变量传递给PHP会话变量。 Thanks 谢谢

No ajax? 没有阿贾克斯? ok, 好,

var img = new Image();
img.src = "script.php?myVal=" + encodeURIComponent(theValueToPass);

The browser will try to load the image by requesting the url. 浏览器将尝试通过请求url加载图像。 Obviously it will be a fools errand, but your php script will get executed and the value available in php's $_GET['myVal'] 显然,这将是一个愚蠢的事情,但是您的php脚本将被执行,并且该值在php的$_GET['myVal']可用

Hmmm, I think, You can do it by adding a cookie value with your javascript, and update your session in php on the NEXT PAGE REFERESH, with reference to that cookie value. 嗯,我想,您可以通过在JavaScript中添加Cookie值来实现此目的,并参考该Cookie值在NEXT PAGE REFERESH上的php中更新会话。

I haven't tried it, and i don't think there is way we can update the session from just client side with javascript. 我还没有尝试过,而且我不认为我们可以通过JavaScript从客户端更新会话。

Thanks 谢谢

You can't really. 你真的不能。

Session data is altered with the server, while Javascript can only alter client-side data (such as cookies). 服务器会更改会话数据,而Javascript只能更改客户端数据(例如Cookie)。 You can, however, create a solution by creating a new PHP page that passes a variable within the GET/POST request, then alters the session. 但是,您可以通过创建一个新的PHP页面来创建解决方案,该页面在GET / POST请求中传递一个变量,然后更改会话。

The only alternative I can think of is using javascript to set a parameter in the URL which you could interpret later with PHP, but that would be after another page load. 我能想到的唯一替代方法是使用javascript在URL中设置一个参数,您稍后可以使用PHP对其进行解释,但这将在另一个页面加载之后进行。

http://www.mine.com/index.html?paramter=variable&anotherparam=anothervariable

see this post for a method to achive this 看到这篇文章的方法来实现这一目标

edit: I don't think this will achive what you after on second thought, but I'll leave the answer just in-case 编辑:我不认为这会在第二次思考后达到您的期望,但我会保留答案以防万一

PHP session variable resides on the server: PHP会话变量位于服务器上:

http://www.w3schools.com/PHP/php_sessions.asp http://www.w3schools.com/PHP/php_sessions.asp

but the JavaScript values are on client-end only. 但JavaScript值仅在客户端上。

There should be a mechanism to send this to server, if not using ajax: try saving this value into a hidden field and then sending it using usual get/post. 如果没有使用ajax,应该有一种机制可以将其发送到服务器:尝试将此值保存到隐藏字段中,然后使用常规的get / post发送。

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

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