I have a link like this: <a href="javascript:window.print();">Print</a>
. I'm trying to increme开发者_如何学编程nt a PHP variable when that is clicked. I could technically do it by submitting a form, but I'm sure there is an easier way. Any ideas?
JavaScript is Client Side. PHP is Server Side. If you want to affect a PHP Variable with a JavaScript event you must issue an AJAX call of some kind.
You'll need to persist a variable like this using some sort of database. You can then issue an AJAX call to a small server-side file that increments a value in that database.
On your HTML page:
<script type="text/javascript">
$(document).ready(function() {
$('#print').click(function() {
$.getJSON('http://somewhere.com/increment.php', null, function(data) {
console.log('remote increment script returned: ' + data);
});
window.print();
});
});
</script>
<a href="javascript: void 0;" id="print">Print</a>
Then, server-side in /increment.php
(I assumed MySQL, but you could use something else like Redis for this as well):
// database connection goes here
$result = mysql_query("UPDATE stats SET stat_value = stat_value + 1 WHERE stat_key = 'prints'", $some_database_connection);
mysql_close($some_database_connection);
die( $result ? 'true' : 'false' );
精彩评论