PHP onclick question?
开发者_JAVA技巧Hi I want to increase value by onclick . my code is:
<?php
$r=0;
function goto()
{
$r++;
}
echo "<input type=button onclick=goto(); value=ClicktoIncrease >";
echo "r value is = $r";
?>
I think the r value increase by clicking.
but it not works.
Anybody know for this solution?
You can not use PHP for doing this. as Pekka said, PHP runs on Server-side, while what you are trying to do is Client-side increment of a variable. Try using Javascript for this:
<script type="text/javascript">
var r = 0;
</script>
and
<button onclick="r++">Increment</button>
The only way to have these HTML and the PHP interact is via a page reload and in storing the value of $r in a session or cookie. This way whenever a person clicks the button the page will refresh and your variable will increase by one. Take this pseudo-code for an example:
<?php
session_start();
if(!isset($_SESSION['r']))
{
$_SESSION['r'] = 0;
}
if(isset($_REQUEST['rincrease']))
{
$_SESSION['r'] += 1;
}
?>
<form>
<p>Current value of 'r' is <?=$_SESSION['r']?>.
Click submit to increase its value.</p>
<input type="hidden" name="rincrease"/>
<submit />
</form>
I'm not in front of a server so can't check this but it looks fine. What it does is have a hidden value within a form that the page checks for when loading. Hitting the submit button will cause the form to post back to itself and to increment the value of the session variable 'r'
The better way to do this would be in-page with JavaScript if you don't need to capture the value of 'r' on the server side. But even if you do, you can submit the value when your form posts and save yourself having to resubmit the page every time you want to increment the value, and also save your user from a lot of page refreshes.
Hope that this is informative.
精彩评论