简体   繁体   中英

Add parameter to URL with Javascript

I have a web page with a jQuery lightbox that opens automatically on page load. In the lightbox I have implemented the Facebook Like button (this is a 2 click solution for Facebook Like button in email). Now, when a Facebook user visits my web page by clicking on the "Liked" URL on Facebook I want to turn off the lightbox. I don't want to have to create two different pages (one with lightbox turned on and another turned off) and I think I can avoid this by adding a parameter to the URL with Javascript then turn the lightbox on/off based on that parameter. Is this a safe way to do this? How would I do this?

You can get URL params with this JS function that I found here :

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;
}

Then *add use ?lightbox=1 eg www.example.com?lightbox=1 and read it with the above function:

if(getUrlVars()["lightbox"]=="1"){
    //...
}

*to add parameters you can either:

  • Change the a link href attribute element.href = "http://www.newURL.com?param=1"; and wait for the user to click them
  • Redirect to the new location window.location.href = "http://www.newURL.com?param=1";

I believe this is the rough code you're after:

<script type="text/javascript">
    document.location="http://example.com/index.php?noLightBox=1";
</script>

Then on index.php, you'd want something such as:

<?php 
function isset_or(&$check, $alternate = NULL) 
{ 
    return (isset($check)) ? (empty($check) ? $alternate : $check) : $alternate; 
} 

function getGETPOST($var) 
{ 
       return isset_or($_GET[$var],isset_or($_POST[$var],"Empty")); 
} 
?>

Example:

if(getGETPOST('noLightBox') != 1) {
// Code to display the light box comes here.
}
// Else normal page code

Hope this was helpful! Source: http://php.net/manual/en/function.isset.php & W3School's tutorials on PHP

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