简体   繁体   English

将 PHP 变量传递给 Javascript 数组

[英]Passing PHP variable to Javascript Array

i want to pass PHP variable to Javascript array.我想将 PHP 变量传递给 Javascript 数组。 It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart The code above is working without printing the button with echo.Any better ideas are welcome :)这是一个测试代码,但我想进一步将打印的产品 ID 和名称传递给这个 ajax 函数以将其发送到购物车上面的代码可以在不打印带有 echo 的按钮的情况下工作。欢迎任何更好的想法:)

 <html>

<?php 

$num=3;

echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";

?>
</html>
<script>

function funkt(x){
 var c=x;
alert(c);
}



</script>

You weren't properly escaping the quotes inside the echo statement.您没有正确转义 echo 语句中的引号。 Also, HTML attributes use double quotes (onclick="..."), not single quotes.此外,HTML 属性使用双引号(onclick="..."),而不是单引号。 Try this:尝试这个:

<!DOCTYPE html>
<html>
<head>    
<script>
    function funkt(x) {
        var c = x;
        alert(c);
    }
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>

Better option is to add an input field of type hidden and pass the number/name/ID to it.更好的选择是添加一个隐藏类型的输入字段并将数字/名称/ID 传递给它。 On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.在提交表单或单击按钮时,您可以使用字段 Id 获取它并将值传递给 ajax。

<input type="hidden" id="number" value="<?php echo $num;?>" />


<script>
    function funkt(x) {
        var c = document.querySelector("#number").value;
        alert(c);
    }
</script>

You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:您可以尝试在“script”标签内声明变量,然后在 javascript 中使用此变量,如下所示:

<?php  $num = 5;  ?>   
    <script>
          var link_label = '<?php echo $num ?>';

          //use your link_label value to load it in ajax here or in other files that has been loaded after this script

    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM