[英]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.