Вопрос

I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.

How can i do this the easiest way?

Here is one thing i have tried:

<script>

var query = window.location.hash;

document.cookies = 'anchor=' + query[1];

<?php if (!$_COOKIE['anchor']) : ?>

window.location.reload();

<?php endif; ?>

<?php

echo $_COOKIE['anchor'];

?>
Это было полезно?

Решение

Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!

var xhr = new XMLHttpRequest();
xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
xhr.onreadystatechange = function() {
    if( this.readyState == 4 && this.status == 200) {
        // do something with this.responseText
    }
};
xhr.send();

Другие советы

The hash part of the URL is not sent to the server, so you need to do so yourself.

The cookies set by the client too are not sent to the server either; the client just remembers them when it talks to the server.

This means that you have to retrieve in Javascript, as you already did, and make an explicit call.

 // Example in jQuery
 jQuery.ajax({
     type: "POST", 
     url: "/path/to/php/script.php", 
     data: {
         hash: window.location.hash
     }
 });

Then in the script.php you receive a $_POST['hash'] variable and can store it in the session. But remember that when you do, the sending page has already been loaded and is "stopped". If you want to trigger a reload, you need to send back some kind of response and react to it in jQuery's return function.

You can't. hashtags don't fly to the server. that's why MEGA site is still alive. hashes live only in the browser.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top