单击按钮即可运行PHP函数吗? [英] Run a PHP function upon button click?

查看:73
本文介绍了单击按钮即可运行PHP函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过单击HTML按钮来运行PHP函数.

I want to run a PHP function with an HTML button click.

我可以这样调用PHP脚本:

I can call a PHP script this way:

<form action="action.php" method="post">
  Name: <input type="text" name="txt"/>
  <input type="submit" />
</form>

但是我不想调用"action.php".我只想调用此页面中定义的PHP函数.能做到吗?

But I don't want to invoke "action.php". I just want to call the PHP function I defined in this page. Can this be done?

推荐答案

我更喜欢使用的方法是jQuery/ajax的混合,调用了面向对象的PHP类.

The method I prefer to use is a mixture of jQuery/ajax calling an Object Oriented PHP class.

对于按钮按下,我有一个jQuery侦听器/触发,如下所示:

I have a jQuery listener/trigger for the button press with something like this:

$('#buttonId').live('click', function() {
    $.get('api.php?functionName=test&inputvar=something');

    return false;
});

这将通过ajax调用api.php文件,并阻止任何进一步的操作,例如表单提交.

That will call the api.php file through ajax and prevent any further action, such as form submission.

然后在PHP文件中,您总是可以做一些基本的事情,例如:

Then in the PHP file you could always do something basic like:

if ($_REQUEST['functionName'] == 'test') {
    test();
}

或者如果您有大量的类和大量的动态输入,则可以做一些更有趣的事情,例如:

or if you have huge classes and alot of dynamic input you could do something more interesting like:

$functionName = $_REQUEST['functionName'];
if (method_exists($myClassInstance, $functionName))
    $myClassInstance->$functionName();

有很多方法可以解决此问题,但这是我的最爱.另一个选择是Extjs框架,它是为这种活动而构建的,但是如果您还不熟悉它,并且该项目不是巨大的",那么我就不会担心自己.

There are numerous ways to approach this, but these are my favorites. Another alternative is the Extjs framework which is built for this kind of activity but if you are not familiar with it already and the project is not 'huge' I would not concern myself with it.

最后,如果您需要从php文件(如json结果)中获取响应,则不要使用jQuery:$.get()函数,而要使用函数$.getJSON

Lastly, if you are needing to get a response back from the php file such as json results, then instead of using the jQuery: $.get() function, use the function $.getJSON

希望有帮助:)

这篇关于单击按钮即可运行PHP函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆