简体   繁体   中英

Transfer javascript var to php var?

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?
$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;
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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