首页 > 解决方案 > 如何将作为id传递给javascript的php变量存储在javascript变量中

问题描述

我正在尝试将 div 传递id给 javascript 并在控制台上将其打印为:

<?php echo 67;?>

67来id了。我想知道如何将这个值存储在我的 javascript 变量storeidvar storeid = 67

我的代码:

 echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";

        echo "<script>

        $('h2.editme').click(function(){
            console.log(this.id);
            var storeid;

        });

        </script>";

另外,我想使用该id值来更新我的 sql 中的值。一旦我能以某种方式获得该 id 的值,我只能测试我的代码。如何存储idto javascript 变量的值?

我的代码(这是在我获得 id 后更新 sql) - 不确定它是否正确我可以在获得id价值后对其进行测试:

 echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";

            echo "<script>

            $('h2.editme').click(function(){
              var content2 = $(this).html();

                console.log(this.id);
                var storeid;//once I get the id
 $.ajax({
                      url: 'updateDescription(storeid, content2)',
                      success: function(respon) {
$('.editme').html(respon);
                      }
                    });

            });
   
            </script>";

function updateDescription($user_unique_id, $content2)
{
    try {
        require "testing.php";
        $sql = "UPDATE icecream  SET
             desc = :desc
             WHERE id = :id";
        $stmt->bindParam(':desc', $content2, PDO::PARAM_STR);
        $stmt->bindParam(':id', $user_unique_id);
        $stmt->execute();
        echo 'Record updated';
    } catch (PDOException $e) {
        echo 'Connection failed ' . $e->getMessage();
    }

}

标签: javascriptphphtmlcss

解决方案


这边走:

echo '<script>
   var storeid = '. $id .'
 </script>';

更具可读性的方式:

// somefile.php
<?php

   $id = 67;

?>

<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>

<script>
  var storeid = <?php echo $id; ?>
  // rest of javascript code
</script>

<?php
 // rest of the php code

推荐阅读