简体   繁体   中英

Issue i'm facing ; Javascript encode with php variables inside

I seem to be having an issue, I have a Javascript code,and it contains php variables

<?php   // Database information 
$name="whatever"; 

$mp3 = "Link/to/track/";
echo "
var myPlaylist = [{
    mp3:'mix/4.mp3',
    title:'$name',
}]]; </script>";

Upon trying to encode this,I'm able to encode the Javascript part, but it displays my variable names (in this instance $name) instead of the value(whatever)

Whenever you're transferring information between PHP and JS like this, use json_encode . 1) You know that you're building a proper JavaScript structure (in your code, you're not...you're closing the array twice), and 2) you protect from escaping issues. Try:

<?php
$name = 'whatever';
$mp3 = '/link/to/track';

$json = array(array('mp3' => $mp3, 'title' => $name));
print "var myPlaylist = " . json_encode($json);

That should work, but try this anyway

title:'".$name."',

or

title:'{$name}',

Since you used double quotes it should render php variables, single quotes wouldn't but you are not using those. Also make sure to escape the name because what if it had a single quote in it? It would break your javascript (unless its strictly controlled and you know for a fact it will not have a single quote in it).

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