简体   繁体   中英

How should I load a js-function based on parameter in url?

* What's the correct approach of handling this? *

What I want to do: Let's say I have an url like:

http://www.domain.com/parties/

This link shows all parties. Each party is clickable and If a user clicks one of them (that has id 54), then this page will show:

http://www.domain.com/party/54

A page would be shown for the specific party 54.

When I'm calling http://www.domain.com/party{id} , I include a javascript-file. In this js-file ( party.js ) I have a function loadParty(party_id) .

I want to load a specific js-function that loads the actual party (54) when calling http://www.domain.com/party/54 (I must use javascript for this (I have to retrieve info about screen resolution etc)).

Should I do?

  1. var party_id = <?php echo $get['id'];>;
  2. Use ajax to call php, that returns the value of $_GET['id'] (and put it into the party_id - js - variable) ?

    And then call loadParty(party_id);

Any other thoughts?

(I'm using jQuery/CodeIgniter if it matters (I do think not))

UPDATE

I was just doing <?php echo $get['id'];>; just to show the principle of what I wanted. I would never just do that, I promise! :-)

The more relevant code would be something like

<?php
if (isset($_GET['id'])) {
    $id = intval($_GET['id']);
    $party = new Party();
    $party_id = $party->doPartyExists($id); //Returns 0 at false
    if (intval($party_id) === 0) {
        throw new Exception('this is not a party');
    }
}
?>

and then put it the $party_id -value into js...

First do this -

<?php

    $id = $_REQUEST['id'];

?>

and then make call the function like this-

loadParty('<?php echo $id ?>');

No need of ajax calls. Btw, you can write both pieces of code in the same file which you load when the url is hit.

@notsobestprogrammerintheword :)

Your approach is good but i have concerns about key in $_GET : it may not be 'id', but 'party' but it depends on routing configuration. And please cast the value from $_GET to INT: make your site immune to XSS attack!

var party_id = '<?php echo isset($_GET["id"]) ? (INT) $_GET["id"]: 0;>';

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