简体   繁体   中英

Execute JavaScript code with PHP $_GET

I have a bit of coding that displays div's when requested through a link, now I want to be able to link to that page, and execute the JavaScript with the parameter given through the url in PHP.

The JavaScript displays and closes div's when requested through links.

Link example:

<a href="#div1" class="selectType">Click here for div1</a>
<a href="#div2" class="selectType">Click here for div2</a>
<a href="#div3" class="selectType">Click here for div3</a>

JavaScript code:

$('.selectType').on('click', function(e){
    e.preventDefault();
    var targetDiv = $($(this).attr('href'));
    if(!targetDiv.is(':visible')){
        $('.hide').slideUp();
        targetDiv.slideDown();
    }else{
        $('.hide').slideUp();
    }
});

css for div:

.hide{display:none;}

div code:

<div id="div1" class="hide">Text in div1</div>
<div id="div2" class="hide">Text in div2</div>
<div id="div3" class="hide">Text in div3</div>

I want to give the URL a link like so:

http://www.example.com/pages/index.php?pageid=div2

When that page is visited, the JavaScript will execute as if the link "Click here for div2" was pressed, so that div2 pops up.

I have no idea where to get started, as in, I do know how to grab the $_GET['pageid'] variable, but no clue how to combine it with the JavaScript into displaying the requested div.

Thanks ahead!

First change your hide/show into a function to save repeating code... ie:

var toggleSelectType = function(target) {
    var targetDiv = $(target);

    if (!targetDiv.is(':visible')) {
        $('.hide').slideUp();
        targetDiv.slideDown();
    } else {
        $('.hide').slideUp();
    }
};

$('.selectType').on('click', function(e){
    e.preventDefault();
    toggleSelectType($(this).attr('href'));
});

Add a function that helps you grab query string values such as: ( How can I get query string values in JavaScript? ) ** credit

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

Then when the page loads check for the value of pageid and run your function:

var pageId = getParameterByName('pageid');
toggleSelectType('#'+pageId);

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