是否可以创建一个像按钮一样的链接,并在点击时执行功能?
In PHP,
I want to execute a function when a hyperlink is clicked. The only way I can think of doing this is by having the link attach a get parameter to the url when clicked and by doing an if statement that checks to see if that parameter exists and if so then have the function executed. But is there a way to do this like:
<a href='#' onclick='<?php functionName(); ?>'>
Obviously there are a million things wrong with this example but is it possible in any other way?
在PHP中, p>
我想在超链接时执行一个函数 点击。 我能想到这样做的唯一方法是让链接在点击时将一个get参数附加到url,并通过执行if语句来检查该参数是否存在,如果存在,则执行该函数。 但有没有办法这样做: p>
&lt; a href ='#'onclick ='&lt;?php functionName(); ?&gt;'&gt;
code> pre>
显然这个例子有一百万个问题但是有可能以其他方式吗? p>
DIV>
Well technically you can't but here is a trick to make it work. You just need to dynamiclly create your javascript. The drawback to this is you can't pass any parameters but it can be convenient at times.
However unless you understand what is going on you will get in to problems. Make sure you understand Johns answer before proceeding.
Observe:
<a href=# onclick="jsPhpFunction();">
<script>
function jsPhpFunction()
{
<?php
$name = query("Select name from table where id = ? ", $_REQUEST[id]);
echo "window.alert('Hello {$name}');";
?>
}
</script>
PHP is executed on the server side so, no, you can't. You'll either need to use JavaScript to perform the function or use Ajax to contact the server and retrieve the results of a PHP script.