开发者

Call PHP method with Ajax.Request

Whats the best way to call a certain method in a PHP file with Ajax.Request (using prototype)? I am submiting a form with Form.serialize, so I thought of adding a parameter (like the name of the method to call) and then check it on the server script. Something like:

var params=Form.serialize("someform")+"&=method='check_data'";
new Ajax.Request('somescript.php',{method:'post',parameters:params,onSuccess开发者_JAVA百科:
function(response)
{ 
    .. do something with the response

And in somescript.php:

if($_POST["method"] == "check_data")
{
    check_data();
...
}

This would work, but Im sure theres a better or simpler way to call a remote method (ala MVC). Any ideas?


Under no circumstances do this for normal PHP methods. It opens a big potential security hole. Even if you limit the commands that can be called that way, it's not a good way to go in the long run.

Either stay with what you already do: Define a list of commands that can be passed to the PHP script (e.g. command=delete, command=update, command=copy, whatever you need), and call them using switch.

Or use a class with methods that can be safely called from outside:

class myCommands
{
  function copy()  {  ... }
  function delete()  {  ... }
  function update()  {  ... }
 }

then, in the PHP file, pass through the command like

if (method_exists($class, $_POST["method"]))  
 call_user_func(array($class, $_POST["method"]));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜