是否可以使用 AJAX POST 数据作为 PHP 类中的构造函数值?

发布于 2024-11-05 12:39:58 字数 390 浏览 4 评论 0原文

我想通过 AJAX 调用 PHP 类来处理一些表单数据。因为当您在 PHP 中实例化一个类时,您可以传入要在类构造函数中使用的值,所以我想知道是否可以通过 AJAX 实现同样的操作?

我目前正在类中使用带有单独函数的 POST 方法来检测后值,然后处理它们,但如果可能的话,我可以通过在构造函数中预加载值来节省时间!

更新:代码示例

class myAjaxClass {
    private $data;
    public function __construct($could, $this, $be, $post, $data) {
        $this->data = $data;
        ...etc...

I want to call a PHP class via AJAX to process some form data. Since when you instantiate a class in PHP you can pass in values to be used in the classes constructor I wondered if the same thing was possible via AJAX?

I'm currently using the POST method with a separate function in the class to detect the post values and then process them, but I could save time by pre-loading the values in the contructor if this is possible!

Update: Code example

class myAjaxClass {
    private $data;
    public function __construct($could, $this, $be, $post, $data) {
        $this->data = $data;
        ...etc...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

朱染 2024-11-12 12:39:58

通过 AJAX 您只能调用一些脚本,例如 my_script.php,它看起来

<?php
$myAjaxClass = new MyAjaxClass($_POST['could'], $_POST['this'], $_POST['be'], $_POST['post'], ...);
var_dump($myAjaxClass);
?>

像在 JS AJAX 调用中您必须提供用于发布的数据,例如使用 jQuery:

$(document).ready(function(){
    $.post(
        "my_script.php",
        {could: "COULD", this: "THIS", be: "BE", ... },
        function(data) {
            alert(data); // data must be a string... when object, use data.property, when array, use data['index']
        }
    );
});

By AJAX You can call only some script, e.g. my_script.php, that will look like

<?php
$myAjaxClass = new MyAjaxClass($_POST['could'], $_POST['this'], $_POST['be'], $_POST['post'], ...);
var_dump($myAjaxClass);
?>

and within JS AJAX call You have to provide the data for post, e.g. with jQuery:

$(document).ready(function(){
    $.post(
        "my_script.php",
        {could: "COULD", this: "THIS", be: "BE", ... },
        function(data) {
            alert(data); // data must be a string... when object, use data.property, when array, use data['index']
        }
    );
});
这个俗人 2024-11-12 12:39:58

后值是超全局变量,因此您不需要将它们传递给任何东西。如果您的ajax请求正在调用正确的obj,您所需要做的就是在该类的方法中使用$_POST...

The post values are superglobals so you don't need to pass them to anything. If your ajax request is calling the correct obj all you need do is use $_POST within the methods of that class...

夏九 2024-11-12 12:39:58

最后,我决定编写一个基本的 Ajax 处理程序类来准备和加载 POST 数据等。然后我可以使用其他类来扩展它以用于特定目的,例如“AjaxLogin”和“AjaxRegister”。

这里是:

class Ajax {

    protected $data = array();
    protected $command; // Used to request a specific method.
    protected $count; // Counter for multi-page forms (Really needed?)

    /**
     * Response is the output array to be serialised using `json_encode()`
     * @var Boolean - Used to imply the success or failure of the AJAX function (i.e. form validation)
     * @var Array (optional) - An array of output / error messages [ Defined as: 'messages' => ... ]
     */
    protected $response = array('valid' => true); // Output to be serialised using 'json_encode()'

    public function __construct() {
        /* Redirect empty or insufficient POST data with 'Forbidden' response header (overwrite false) */
        if( !$_POST OR count($_POST) < 1 ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();     
        }

        /* Session validation (if 'hash' sent) */
        if( isset($_POST['hash']) AND $_POST['hash'] != md5(session_id()) ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();
        }

        $this->processRequest($_POST['data']);
    }

    protected function addMessage($message) {
        $this->response['valid'] = false;
        $this->response['messages'][] = $message;
    }

    /**
     * Unserialise AJAX data. Accepts data from either:
     * - jQuery.serialize()         [String]
     * - jQuery.serializeArray()    [Array of Objects]
     */
    private function unserializeData($data) {
        // -- from jQuery.serialize()
        if( is_string($data) ) {
            $array = explode('&', $data);
            foreach($array as $key => $value) {
                $string = preg_split('/=/', $value);
                $this->data[$string[0]] = $string[1];
            }
        }
        //  -- from jQuery.serializeArray()
        elseif( is_array($data) ) {
            $array = (array) $data;
            foreach($array as $element) {
                $this->data[$element['name']] = $element['value'];
            //  $this->addMessage($element['name'].' => '.$element['value']);
            }
        }
        else $this->addMessage('Unable to process your request, Please contact our Technical Support!');
    }

    // TODO: Use strip_tags or something for security??
    private function processRequest($data) {
        /* Process serialised data in to an Array */
        $this->unserializeData($data);

        /* Process additional POST data (if present) */
        if( isset($_POST['command']) ) $this->command = $_POST['command'];
        if( isset($_POST['count']) ) $this->count = $_POST['count'];
        // Add additional POST data processing here!!
    }
}

随意使用、修改、做出判断等,只要你认为合适,我希望这对某人有帮助! ;)

In the end I decided to write a base Ajax handler class to prepare and load the POST data etc. I can then extend this with other classes for specific purposes such as 'AjaxLogin' and 'AjaxRegister'.

Here it is:

class Ajax {

    protected $data = array();
    protected $command; // Used to request a specific method.
    protected $count; // Counter for multi-page forms (Really needed?)

    /**
     * Response is the output array to be serialised using `json_encode()`
     * @var Boolean - Used to imply the success or failure of the AJAX function (i.e. form validation)
     * @var Array (optional) - An array of output / error messages [ Defined as: 'messages' => ... ]
     */
    protected $response = array('valid' => true); // Output to be serialised using 'json_encode()'

    public function __construct() {
        /* Redirect empty or insufficient POST data with 'Forbidden' response header (overwrite false) */
        if( !$_POST OR count($_POST) < 1 ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();     
        }

        /* Session validation (if 'hash' sent) */
        if( isset($_POST['hash']) AND $_POST['hash'] != md5(session_id()) ) {
            header('location:'.$_SERVER['HTTP_REFERER'], false, '403');
            exit();
        }

        $this->processRequest($_POST['data']);
    }

    protected function addMessage($message) {
        $this->response['valid'] = false;
        $this->response['messages'][] = $message;
    }

    /**
     * Unserialise AJAX data. Accepts data from either:
     * - jQuery.serialize()         [String]
     * - jQuery.serializeArray()    [Array of Objects]
     */
    private function unserializeData($data) {
        // -- from jQuery.serialize()
        if( is_string($data) ) {
            $array = explode('&', $data);
            foreach($array as $key => $value) {
                $string = preg_split('/=/', $value);
                $this->data[$string[0]] = $string[1];
            }
        }
        //  -- from jQuery.serializeArray()
        elseif( is_array($data) ) {
            $array = (array) $data;
            foreach($array as $element) {
                $this->data[$element['name']] = $element['value'];
            //  $this->addMessage($element['name'].' => '.$element['value']);
            }
        }
        else $this->addMessage('Unable to process your request, Please contact our Technical Support!');
    }

    // TODO: Use strip_tags or something for security??
    private function processRequest($data) {
        /* Process serialised data in to an Array */
        $this->unserializeData($data);

        /* Process additional POST data (if present) */
        if( isset($_POST['command']) ) $this->command = $_POST['command'];
        if( isset($_POST['count']) ) $this->count = $_POST['count'];
        // Add additional POST data processing here!!
    }
}

Feel free to use, modify, pass judgement etc. as you see fit, I hope this helps someone! ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文