[英]How to display the value of a php variable by clicking on a hyperlink
我想在用户单击超链接时显示其余额。 用户的余额存储在php变量中。 我希望可以使用javascript完成此操作,但是我在javascript方面没有太多经验。
下面是我的代码:
$userbalance = $xyz[2];
echo "Your balance stands at ".$xyz[2];
这个东西正在工作,但是我想通过单击链接来显示$userbalance
我不知道在锚标记中放什么。
通过单击超链接,是否有可能显示php varibale的值?
我可以将函数传递给href
吗? 还是可以通过某种方式使用onclick
?
尝试这个:
<a href="somepage.php?balance=<?php $balance = $xyz[2]; echo "Your balance stands at ". $balance; ?>" >Click</a>
通过以上方法,您可以在任何页面的url中显示余额。 然后,如果需要使用该余额,只需使用超级全局变量$_GET['balance'];
即可获得该值$_GET['balance'];
以最简单的形式 ,可以通过将值存储在HTML支持的“ data-”属性中,然后使用Javascript在用户单击时提醒该值来完成此操作。
<p>
Click to see your account
<a href="javascript:void();" data-balance="123 €" onclick="window.alert(this.getAttribute('data-balance'))">balance</a>.
</p>
PHP的一部分只是将正确的平衡返回到以上HTML代码中的正确位置。
<a href="javascript:void();" data-balance="<?= $balance ?>" onclick="window.alert(this.getAttribute('data-balance'))">balance</a>.
最终HTML的示例: https : //jsfiddle.net/oh8jnmg2/1/
如果您不想实际使用两个页面,但仍然显示新内容并隐藏其他所有内容,则可以使用此解决方案:
$userbalance = $xyz[2];
echo `Your balance stands at <a href='javascript:{document.documentElement.innerHTML = ""; document.write(` . $xyz[2] . `);}'>see variable</a>`;
如果只想在下面显示一个新值,请使用:
$userbalance = $xyz[2];
echo `Your balance stands at <div id="myDiv"><a href='javascript:{document.getElementById("myDiv").innerHTML = ` . $xyz[2] . `;}'>see variable</a></div>`;
零食给出了正确的提示。 但我不建议将输出字符串放入链接,该链接会显示在url中。 由于HTML是通过PHP呈现的,因此您只需输入以下内容即可将值附加到链接:
<a href="yourprintsite.php?balance=$userbalance>Click here to see your balance</a>
然后在yourprintsite.php上,您只需键入:
if (!empty($_GET['balance')) {
echo "Your balance stands at " . $_GET['balance'];
}
这样就完成了。
您可以编写下一个代码吗,函数getAttribute必须帮助您
<script type="text/javascript">
function clickHanler(d){
alert(d.getAttribute("data-userbalance"));
}
</script>
<a
data-userbalance="21"
href="#"
onclick="clickHanler(this);">
Click to do something
</a>
首先,让我们从HTML开始,您需要创建一个<a></a>
并路由到no where:
<a href="javascript:void(0)" id="linktobalance">Click to see Balance</a>
然后,在Javascript部分:
我们需要使用Ajax调用来从balance.php
页面获取balance
:
$("#linktobalance").on("click", function(){ $.post( "balance.php", function(balance) { //In this part, the balance is the value returned from th PHP, you can do whatever with it, I'll alert it alert( "The user balance is "+balance ); }); });
注意 :我们使用jQuery ,您可以通过执行以下操作将其添加到项目中:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
$("#showbalance").click(function(){ $("#balance").show(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> <a href="#" id="showbalance">Show Balance</a> <div id="balance" style="display: none;"> Balance = 1000 </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.