Load a different JavaScript file according to lang

2019-09-18 14:12发布

I'm trying to add a cookie banner to my website and it has two different languages: Italian and English.

Language goes as

http://www.grcparfum.it/home.php?section=letteradelpresidente&lang=eng

and

http://www.grcparfum.it/home.php?section=letteradelpresidente&lang=ita

and this is my code:

<?php
   $currentlang= $_GET['link'];
   if($currentlang !=eng){
    ?>   
    <script src="/js/cookiechoices-en.js"></script>

   }
<?php else: ?>{
<script src="/js/cookiechoices-it.js"></script>
<?php endif; ?>
   }

3条回答
霸刀☆藐视天下
2楼-- · 2019-09-18 14:47

Problems you're probably encountering:

  • Some curly brackets are outside of the scope of PHP
  • It looks like you should be using == for the first if statement not !=.
  • You're trying to compare a constant called eng with $currentlang rather than "eng"

Try:

<?php
   $currentlang = filter_input(INPUT_GET, 'lang', FILTER_SANITIZE_STRING); // Safer
   if($currentlang == "eng"){ ?>   
        <script src="/js/cookiechoices-en.js"></script>
    <?php } else { ?>{
        <script src="/js/cookiechoices-it.js"></script>
    <?php }
?>
查看更多
贪生不怕死
3楼-- · 2019-09-18 14:57

I'm assuming it's never picking the eng option.

I think your bug is not putting eng in quotes:

if($currentlang !=eng){

Should be

 if($currentlang != "eng"){
查看更多
地球回转人心会变
4楼-- · 2019-09-18 15:00

Do this using JQuery:

url = 'http://www.grcparfum.it/home.php?section=letteradelpresidente&lang=eng';

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(url);
  // results = regex.exec(location.search); gets the url of current window

    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var language = getParameterByName('lang');
english = '<script src="/js/cookiechoices-en.js"><\/script>';
italian = '<script src="/js/cookiechoices-it.js"><\/script>';
if(language == 'eng'){
    $('#script').html(english);
}else if(language == 'ita'){
    $('#script').html(italian);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="script"></div>

查看更多
登录 后发表回答