Transfer javascript var to php var?

﹥>﹥吖頭↗ 提交于 2019-12-13 03:39:14

问题


As i would like to determine whether theres a # in the link, and you only can do this in Javascript, I would like to transfer a JS variable to PHP.

So if i have:

if(location.hash){
var hash = location.hash; 

the hash var needs to be turned in to a php $hash var..

I also tried if not possible, sending in post the variable,

$.post('photo.php?mode=grab', { hash: hash }, function(result) { 
// ..but then i got stuck, how should i transfer to php var from here?

回答1:


$hashVar = $_POST['hash'];

This what you're after?

$("#trigger").click(function(){
var hash = location.hash; 

 $.ajax
  ({
  type: "POST",
  url: "file.php",
  data: hash,
  //cache: false,
  success: function(html)
   {
    alert(html);
   }
  });

 return false;
});



回答2:


The posted string will be available to PHP in the $_POST variable.

Since you're posting a Javascript object using JQuery, PHP should receive it as a JSON string.

You can convert the JSON string into a PHP array using the PHP function json_decode().

Similarly, if you need to send an array back from PHP to Javascript, use json_encode() in PHP to reverse the process and create a JSON object.



来源:https://stackoverflow.com/questions/4713404/transfer-javascript-var-to-php-var

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!