简体   繁体   中英

Passing encoded variable from php and decoding in javascript?

I have a very ugly piece of code in php that does something like this:

for ($i = 0; $i <= ($fi_int-1); $i++) {
        $song_uri = urlencode($songs[$i]);

        echo "URI: " . $song_uri . "<br>";
        echo "<li><a href='#' onclick='PlaySong(".$song_uri.")'>" . $songs[$i] . "</li><br>";
    } 

Now when PlaySong() is being called, this happens:

<script>

            function PlaySong(title) {
                title = decodeURIcomponent(title));
                document.getElementById("player").src = "./mp3/" + title;
            }

</script>

The current problem is when $songs[$i] is being passed to PlaySong(), it looks like that right away:

PlaySong(Name+Of+The+Song+-+Artist+LastName+blah) {
  ...
}

So JS obviously has a problem with it. It tries to add things, because there are pluses... Now how can I convert that mess to string right when it comes in? Or is there a better way to do it? I'm sure there is but this ugliness is strictly for me, so I don't care too much about fast performance :)

You need some quotes around the song_uri string. I can't paste code on mobile... but the php should output like this

Onclick="PlaySong ('this+song')"

At the moment you've got it doing

Onclick="PlaySong(this+song)" and the argument isn't being treated as a string

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