简体   繁体   中英

best way to handle ajax requests in php

it is a good way, to call php functions via javascript?

My POST Data looks like:

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

And my Ajax class looks like this:

<?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. 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

Just check the function that coming from 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. If you changed something on your PHP side, you'll have to change something on your JavaScript side. It's better to ask the PHP software to do something, but you don't care how it does that.

For instance, you could define a public interface for your JavaScript, the public interface are URLs. 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.

The user class handles things related to users:

<?php

interface UserInterface {

  public function toggleStatus();

}

The AJAX class handles the AJAX calls:

<?php

class AJAX {

  public function handle() {

  }

}

Separation of concern is important here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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