[英]Trying to send two values from php to JS
Im retrieving a value from my db, displays on screen as a 0.我从我的数据库中检索一个值,在屏幕上显示为0。
echo "<article>" . $gr_display['status'] . "</article>";
Then when im clicking on this DIV i want to send both status and id to my JS function, edit.然后当我点击这个 DIV 时,我想将状态和 id 发送到我的 JS 函数,编辑。 The ID of this object is 79这个对象的ID是79
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Then the start of my script然后开始我的脚本
function edit(status, id) {
console.log(status, id ); some code later }
But im ending up with the result that id and status is combined into one sett of value, leaving the other one "undefined"但我最终得到的结果是 id 和 status 被组合成一组值,而另一组“未定义”
From console log: 0.79 undefined从控制台日志: 0.79 未定义
Please make a clarity between PHP and JavaScript.请明确 PHP 和 JavaScript 之间的关系。 You need to use the right separator and separate.您需要使用正确的分隔符并分开。
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . " )'> </div>";
//-----------------------------------------------------^
Replace .
替换.
with ,
.与,
. Also please use >
for the opening <div>
.也请使用>
来打开<div>
。 You forgot to close your opening div
.您忘记关闭打开的div
。
you have at typo change the .
你在错字处更改了.
into ,
between the 2 variables into ,
在 2 个变量之间
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )'> </div>";
//---------------------------------------------------------^
or better use data-attributes或者更好地使用数据属性
echo "<div class='edit-element' data-status='" . $gr_display['status'] . "' data-id='" . $gr_display['id'] . "'></div>";
$('.edit-element').click(function(){
console.log($(this).attr('data-status'),$(this).attr('data-id'));
});
用这个替换 div:-
echo "<div onclick='edit( " . $gr_display['status'] . "," . $gr_display['id'] . " )' </div>";
The problem is causes by this line:问题是由这一行引起的:
echo "<div onclick='edit( " . $gr_display['status'] . "." . $gr_display['id'] . " )' </div>";
Notice that between the two arguments you put a '.'请注意,在两个参数之间放置一个 '.' instead of a ',' (a comma).而不是“,”(逗号)。 That way, the second argument in your JS function does not have a value这样,您的 JS 函数中的第二个参数就没有值
Your code has two issues您的代码有两个问题
- You haven't close opening div tag你还没有关闭打开的 div 标签
- Use , to separate two parameters使用 , 分隔两个参数
echo "<div onclick='edit( " . $gr_display['status'] . ", " . $gr_display['id'] . ")'>ddd </div>";
<script type="text/javascript">
function edit(status, id) {
alert(status);
alert(id);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.