OnClick事件中的PHP脚本

PHP Script in OnClick Event

本文关键字:PHP 脚本 事件 OnClick      更新时间:2023-09-26

这是IS通过onclick事件调用php函数的重复,但我对此有疑问。我有疑问的答案是通过timpanix,基本上它不起作用。

他说要在点击事件中执行一些PHP代码,请执行以下操作:

onclick="document.write('<?php //call a PHP function here ?>');"

并调用PHP函数。然而每当我尝试时:

<button id="profileinformationbutton" input type="submit" value="Login" onclick="document.write('<?php profileupdated() ?>');"> Update Profile </button>

它打印出');" > Update Profile,但我不知道为什么。它位于表单内部,PHP函数如下所示:

<?php
    function profileupdated() {
?>
        <div id="profileupdated"> Profile Updated </div>
<?php
    }
?>

为什么代码会显示这个?请帮忙!:)非常感谢。

编辑

代码似乎没有将Profile Updated写入页面,知道为什么吗?

    function profileupdated() {
        echo "<div id='profileupdated'> Profile Updated </div>";
    }

另外,如果你只想把这个值打印到你的标签上,为什么要使用函数?将其指定给一个变量。

$myVar = '<div id="profileupdated"> Profile Updated </div>';

然后在需要的地方使用这个变量?

你应该回声或返回你的功能体。小心!我更改了引号!

您的PHP函数已经在向页面写入,导致document.write(javascript)变得无用。试试这个:

<?php 
    function profileupdated() {
        return "<div id='profileupdated'>Profile updated</div>";
    } 
?>

不过,我想指出的是,您可能需要考虑一种更干净的方法:如果您只想显示固定文本("Profile updated"),请坚持使用纯客户端Javascript。

否则(如果需要在服务器端执行逻辑),您可能需要将服务器和客户端解耦,并使用AJAX调用和JSON来传输数据。

PHP是一种服务器端编程语言,您在客户端执行JavaScript。如果你想从JavaScript中调用PHP脚本,你需要Ajax,比如jQuery。