简体   繁体   English

处理PHP中的Ajax请求的最佳方法

[英]best way to handle ajax requests in php

it is a good way, to call php functions via javascript? 这是通过JavaScript调用php函数的好方法吗?

My POST Data looks like: 我的POST数据如下:

{
    0: [
        {
            "name": "function",
            "value": "toggle_user_status"
        }
    ],
    1: [
        {
            "name": "user_id",
            "value": "1"
        }
    ],
    ...
    ...
}

And my Ajax class looks like this: 我的Ajax类如下所示:

<?php
class Ajax
{
        public function handleAjax() {
                $load_function = $_POST['function'];
                return call_user_func(array($this,$load_function));
        }

        private function toggle_user_status() {
                return '555nase';
        }
}

i know the $_POST var is not safe, but that's not the point. 我知道$ _POST var不安全,但这不是重点。 i would like to know if that a good way to call the function or not...? 我想知道这是调用函数的好方法吗?

PS: the url http://local.yolo/admin/ajax accepts only request from a logged-in administrator PS:URL http://local.yolo/admin/ajax仅接受来自登录管理员的请求

Just check the function that coming from js. 只需检查来自js的功能。 use something like this: 使用这样的东西:

<?php
    class Ajax
    {
        private $_allowed_functions = array('toggle_user_status');

        public function handleAjax() {
            $load_function = $_POST['function'];
            return in_array($load_function, $this -> _allowed_functions) ? call_user_func(array($this,$load_function)) : NULL;
        }
    }

I understand that you aren't concerned about the security implications and that you're aware of them. 我了解您并不担心安全隐患,并且已经意识到了这些隐患。 Still, it's not a good idea. 不过,这不是一个好主意。 The reason is, your JavaScript must know the PHP implementation. 原因是,您的JavaScript必须知道PHP实现。 If you changed something on your PHP side, you'll have to change something on your JavaScript side. 如果您在PHP方面进行了更改,则必须在JavaScript方面进行更改。 It's better to ask the PHP software to do something, but you don't care how it does that. 最好 PHP软件做某事,但是您不在乎它是如何做到的。

For instance, you could define a public interface for your JavaScript, the public interface are URLs. 例如,您可以为JavaScript定义一个公共接口,该公共接口是URL。 You don't care how they handle anything, you simply want to get a response that also follows a public interface you defined. 您不在乎他们如何处理任何内容,您只想获得一个响应,该响应也遵循您定义的公共接口。 For instance for your example: 例如,您的示例:

jQuery.post("/admin/user/toggle-status", { id: 1 });

The URL is the public interface at this point. 此时,URL是公共接口。

The user class handles things related to users: 用户类处理与用户有关的事情:

<?php

interface UserInterface {

  public function toggleStatus();

}

The AJAX class handles the AJAX calls: AJAX类处理AJAX调用:

<?php

class AJAX {

  public function handle() {

  }

}

Separation of concern is important here. 关注点分离在这里很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM