简体   繁体   中英

Javascript command/variable based on Webpage Domain/Site

I'm using the following code for fetching a latest tweet but I would like the TWITTERUSERNAME to be different depending on the domain it is on as it's a template that is being called from one place but used across multiple domains.

<script type="text/javascript">
    jQuery('document').ready(function() {
        jQuery.getJSON('http://twitter.com/statuses/user_timeline/TWITTERUSERNAME.json?callback=?', function(data) {
             jQuery('#tweet').html(data[0].text);
        });
    });
</script>

I'm guessing just some kind of if statement in php to replace the TWITTERUSERNAME value in the script?

Any pointers on this would be great

Something like:

<script type="text/javascript">
  jQuery('document').ready(function() {
<?php
  $usernames = array(
    'domain.com'      => 'twittername1' ,
    'otherdomain.com' => 'twittername2' ,
    'default'         => 'fallbacktwittername'
  );
  if( isset( $usernames[$_SERVER['SERVER_NAME']] ) ){
    $twittername = $usernames[$_SERVER['SERVER_NAME']];
  }else{
    $twittername = $usernames['default'];
  }
?>
    jQuery.getJSON('http://twitter.com/statuses/user_timeline/<?php echo $twittername; ?>.json?callback=?', function(data) {
       jQuery('#tweet').html(data[0].text);
    });
  });
</script>

Caveats/Warnings The details in the array ("domain.com","otherdomain.com") would not match any contained subdomains (so "www.domain.com" and "www.otherdomain.com" would be seen as not being the same as "domain.com" and "othersomain.com").

if you want to do this in php then you can check against the servername

<?php
if($_SERVER['SERVER_NAME'] == 'www.example.com'){
    $twit = 'username';
}
?>

then your javascript would be something like

    <script type="text/javascript">
    jQuery('document').ready(function() {
        jQuery.getJSON('http://twitter.com/statuses/user_timeline/<?=$twit?>.json?callback=?', function(data) {
             jQuery('#tweet').html(data[0].text);
        });
    });
</script>

Something like:

if($_SERVER['SERVER_NAME'] == "MyServer")
{
  $username = 'Username1';
} elseif($_SERVER['SERVER_NAME'] == "MySecondServer")
{
  $username = "Username2";
} else
{
  $username = "DefaultUsername";
}

and then you use $username as the twitterusername.

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