通过单击按钮将 PHP 字符串变量传递给 Javascript 函数

Pass PHP string variables to Javascript function via button click

我正在动态创建多个按钮,我需要通过 onclick 方法将一些 PHP 变量传递给 JavaScript 函数。

下面的代码大部分工作正常,但如果变量包含双引号或单引号,则无法调用该函数。

我尝试将 htmlspecialcharactersENT_QUOTES 一起使用,这解决了双引号的问题,但单引号仍然导致它失败。

<button id="modalBtn" type="button" onclick="ShowProduct('<?php echo $title ?>', '<?php echo $description ?>', '<?php echo $img ?>');">View Details</button>

关于如何解决这个问题有什么建议或者有更好的方法吗?

我建议你从变量中创建 json 对象并将其作为参数传递,例如:

<button 
    id="modalBtn" 
    type="button" 
    onclick="ShowProduct(<?php echo json_encode(array($title, $description, $img))?>);">
        View Details
</button>

或(更易读的键)

<button 
    id="modalBtn" 
    type="button" 
    onclick="ShowProduct(<?php echo json_encode(array('title' => $title, 'descr' => $description, 'img' => $img))?>);">
        View Details
</button>

你的 ShowProduct 函数你可以这样定义:

function ShowProduct(params) {
    console.log( params );

    // do other stuff
}

更新:

如果您的变量已经在数组中,您可以:

// pass this array:
ShowProduct(<?php echo json_encode($your_array)?>)

// fill new array with required keys only
ShowProduct(<?php echo json_encode(array($your_array['title'], $your_array['description'], $your_array['img']))?>)

我会建议将变量从按钮点击或任何其他事件传递到 javascript 的最佳方法。

在按钮中添加传递参数作为数据属性。

示例:

<button id="b1" type="button" data-id="123" data-name="xyz" data-size="m" onClick="doSomething()">

并且在 php 脚本或 ajax 请求中,您可以获得如下属性:

var id   =  $("#b1").attr("data-id");
var name =  $("#b1").attr("data-name");

并使用 ajax 调用 php 脚本。

希望这就是您要找的。