javascript - 如何将作为id传递给javascript的php变量存储在javascript变量中
问题描述
我正在尝试将 div 传递id
给 javascript 并在控制台上将其打印为:
<?php echo 67;?>
67来id
了。我想知道如何将这个值存储在我的 javascript 变量storeid
中var 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 的值,我只能测试我的代码。如何存储id
to 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();
}
}
解决方案
这边走:
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
推荐阅读
- javascript - 如何在 div 网格中获取元素的行和列
- python - 股票收益的 PCA
- java - 是否可以将 gedit 文本编辑器与 Java LibGDX 一起使用?
- sql - 需要帮助 _ 错误 - 无法计算值并消除带有 0 的值
- java - SocketException:每个请求都重置连接+ Spring集成
- javascript - 当我点击浏览器的返回按钮时创建个性化的确认信息
- android - AppWidget 中的旋转文本
- swift - 如何快速编写 10 项的 Bessel 函数代码?
- python - 将元素动态添加到多维python列表
- python - 如何使用 pandas.read_csv( ) 读取原来的行名?