Concatenation php string to javascript string

非 Y 不嫁゛ 提交于 2019-12-12 00:56:37

问题


I have some question about concatenation php string to javascript string ...

for example:

php variable

$man = "Jamse";

and have javascript function

<script>
    if (document.getElementById("fname").value == "") {
        q = false;
        msg = <?php echo 'Please fill first name'.$formErrors['fname'].'\n' ?>;
    }
</script>

i want to do something like this can anyone help me ?


回答1:


alert('my name is: <?php echo $man; ?>' );




回答2:


alert('my name is: <?= $man; ?>');

Since PHP will insert $man on the server side, it's not a separate string that must be combined by JS. All the browser will see is

alert('my name is: Jamse');



回答3:


Why not write it all in php?

<?php
$man = "Jamse";
echo "<script>
function alertMyName() {
    alert('my name is:" . $man . "');
}
</script>";
?>



回答4:


The other answers are true, I just forgot to write quotes and javascript did not understand it was a String and gave me an error. The correct code:

   if (document.getElementById("fname").value == "") {
        q = false;
        msg = "<?php echo 'Please fill first name'.$formErrors['fname'].'\n'; ?>";
    }


来源:https://stackoverflow.com/questions/22563113/concatenation-php-string-to-javascript-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!