【问题标题】:Access PHP method from HTML onclick event从 HTML onclick 事件访问 PHP 方法
【发布时间】:2016-07-05 16:18:50
【问题描述】:

我正在尝试开发一个网页 (menu.php),当点击访问 stock-c.php 中的众多方法中的“一个”时,该网页具有 <div>。我开发的代码如下:

menu.php

<?php 
require_once '../control/stock-c.php';
?>
<html>
<body>
    <div onclick="<?php $obj=new StockController(); $obj->checkAccessRights();?>">  //I know this is a wrong implementation
       //some code here
    </div>
</body>
</html>

股票-c.php

class StockController{
    public function checkAccessRights(){
        //some code here
    }
    public function getPID(){
        //some code here
    }
}

我知道menu.php 文件的onclick 事件是错误的实现。

由于在其他 PHP 网页中我将需要调用其他方法(如 getPID()),因此我不确定是否使用 jQuery 在 @ 中的 onclick 事件上创建 AJAX 调用987654333@ 访问“更改的”stock-c.php 文件,例如:

class StockController{
    $obj=new StockController();
    $obj->checkAccessRights();

    public function checkAccessRights(){
        //some code here
    }
    public function getPID(){
        //some code here
    }
}

How to Call PHP Function in a Class from HTML Button Click 中提出的建议会起作用,因为这会破坏我访问其他功能的能力。我只是不确定我有什么选择。任何帮助将不胜感激。

【问题讨论】:

  • 我听不懂你的问题,真的:(
  • 嗯...对不起。基本上我想更改“Agha Umair Ahmed”在stackoverflow.com/questions/21304054/… 中发布的解决方案,以便我可以指定访问Awards.php 页面中的任何方法(在我的情况下为stock-c.php)。
  • 您将不得不对调用您的方法的 php 脚本进行 ajax 调用,这是其他问题所暗示的。
  • php.net/manual/en/functions.variable-functions.php你见过吗,你可以把它和一个get请求结合起来。 @user3889963
  • 不可能。 PHP 在服务器上运行。您可以通过单击客户端浏览器中的某些内容来调用 php 代码。最多你可以做一个ajax请求/表单提交将最终在服务器上运行PHP代码。

标签: javascript php jquery oop


【解决方案1】:

在脚本中调用不同方法的一种方法是使用 PHP 的variable functions。这将允许使用 get 或 post 请求调用脚本,并使用输入来选择要调用的函数。

来自 php.net:

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

出于安全原因,最好使用类似 switch 语句或其他限制输入的方式来防止用户调用任意函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多