如何将PHP变量赋给Javascript?

au9on6nz  于 2023-01-11  发布在  Java
关注(0)|答案(5)|浏览(153)

我正在寻找一种更好的方法来将PHP变量发送到Javascript。目前我在PHP中回显该变量:

<script>
  var numbers = <?php echo $numbers ?>;
</script>

然后我在Javascript中访问这个变量,如下所示:class.method(numbers);
我的PHP文件包含在index.php中,在javascript文件之前,所以我可以访问javascript文件中的这个变量。
现在我正在寻找一种比使用echo更好的方法来提交PHP变量。有人有主意吗?
数字的输出如下所示:

vxqlmq5t

vxqlmq5t1#

如果你想把你的php和JS混在一起.你用过的那个更好.你也可以试试这样的方法在你的html页面上添加一个不显示的span,id:document_target example

<span id="document_target" style="display: none;"><?=$numbers;?></span>

在js文件中获取带有id的span数据

var myNumber = document.getElementById("document_target").textContent;
mwecs4sa

mwecs4sa2#

以下是一种可行的方法:
1.如果有表单,从表单字段中获取值,或者其他什么,然后通过查询从JS发送到php,无论php文件在哪里,它都可以工作,它可以是不同服务器上的远程文件,或者只是另一个本地页面,等等。

  1. php文件接收请求并回复
    1.获取JS中php文件的回复。
    上面使用jquery的一个例子:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

        $(document).ready(function(){
            $("#submit_button").change(function(){
                var my_id = "some value here, or do some getelement by id .val()..."
                
                $.ajax({
                    url: 'includes/forms.php', //or replace with a remote url
                    method: 'post',
                    data: {  some_requestPHP_name: my_id } //note this line
                }).done(function(data){
                    console.log(`js got from php =${data}` )
                    //
                      var numbers = data;

                    
                })
            })
        })

现在,在php文件中,您需要使文件在收到包含上面提到的some_requestPHP_name行的内容时做出React,这是您决定的参数

if (isset($_POST["some_requestPHP_name"]))  echo  some_function(); // you can use the "some_requestPHP_name" just as a trigger to call the some_function of you can use the data from it

function some_function(){
// do things and return the number;
return 1;
}

根据您的使用情况,您可能没有表单/按钮等,因此您可能希望删除.change()并立即执行该函数,此时您可以根据需要调整示例。

fv2wmkja

fv2wmkja3#

您可以使用内联脚本标记向HTML文档添加数据,如下所示:

const dataElement = document.querySelector('#phpData'),
  data = JSON.parse(dataElement.text);
  
console.log(data.example, data.number);
<!-- This tag is what really is rendered on the page -->
<script type="text/plain" id="phpData">
{
  "example": "Example string",
  "number": 10
}
</script>

<!-- This tag is written in the source code of the page -->
<script type="text/plain" id="phpData">
{
  "someValue": <?=$some_value?>,
  "otherValue": <?=$other_value?>
}
</script>

可以看出,运行该示例时,JS类型属性不合适的脚本没有执行。
在该脚本标记中,您可以根据需要回显变量或其他值(就像后面的例子),或者甚至回显一个json_encode d字符串。这是将PHP变量包含到JS中最安全的方法之一,并且您仍然可以将实际JavaScript保存到外部文件中。数据脚本必须包含在HTML文档中,因为您无法使用PHP访问. js文件,并且出于安全原因,JS无法从外部文件读取text
至于echo的用法,它是一个PHP语言构造,专门用于向标记添加内容,没有理由避免它。在后一个示例中,我使用了echo的简写,但它仍然是echo

hfsqlsce

hfsqlsce4#

一个更好的替代方法是将PHP值输出到data属性中,假设这个变量似乎没有绑定到特定的元素,可以将它放在body元素的根级别,然后在加载DOM后执行JS时可以从那里读取它,如下所示:

<body data-numbers="<?php echo $numbers ?>">
   <!-- your HTML ... -->
</body>
let numbers = document.body.dataset.numbers; // plain JS

let numbers = $('body').data('numbers'); // jQuery

这是在假设PHP中的$numbers变量持有一个可以强制转换为字符串的值的情况下进行的

  • -* 更新 *--
    考虑到您对问题的编辑,您澄清了$numbers实际上包含一个对象,您可以将其编码为JSON,输出到<script>标记,然后从那里使用它:
    一个二个一个一个
e4eetjau

e4eetjau5#

我是这样做的:

<script src="./assets/scripts/tableActions.js"></script> <!-- JS SCRIPT -->
<table class="w-full" id="table">
                <thead>
                    <tr><th class='border-b p-2 w-52 border-gray-400'>Full Name</th><th class='border-b border-l p-2 w-52 border-gray-400'>Username</th><th class='p-2 border-l border-b w-36 border-gray-400'>Role</th><th class='p-2 border-l border-b border-gray-400'>E-mail</th></tr>
                </thead>
                <tbody>
                <?php
                    include('./functions/connectSQL.php');
                    $sql = "SELECT * FROM users";
                    $result = mysqli_query($con, $sql);
                    $x = 1;
                    while ($row = mysqli_fetch_assoc($result)) {
                        
                        echo "<tr class='hover:bg-gray-800 cursor-pointer' onClick='returnValues(".$x.");' id='tableRow'><td class='border-t p-2 px-4 border-gray-400' id='fullnameCell'>" .$row["fullname"]  . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='usernameCell'>".$row["username"]."</td><td class='border-l border-t p-2 px-4 border-gray-400' id='roleCell'>" . $row["role"] . "</td><td class='border-l border-t p-2 px-4 border-gray-400' id='emailCell'>" . $row["email"] . "</td></tr>";
                        $x++;
                    }
                    mysqli_close($con);
                ?>
                </tbody>
            </table>

看,onClick='returnValues(".$x.");'在它自己里面有来自PHP的变量。所以你要用函数把variable给javascript。现在你可能知道了:

function returnValues(x){
    const table = document.querySelector('table');
    const cells = table.querySelectorAll('td');
    const values = Array.from(cells).map(cell => cell.innerText);
    var tableRow = document.getElementById("table").rows;
    var form = document.getElementById("form");
    const usernameField = document.getElementById('usernameForm');
    for (i = 0; i < tableRow.length; i++){
        let tableCells = tableRow[x].cells[i].innerHTML;
        form.elements[i].value = tableCells;
    }

    if(values.includes(usernameField.innerText)){
        formButtonAdmin.innerText = "Update";
    }
}

现在你可以很好,当你有任何其他问题,随时问:D祝你有美好的一天!

相关问题