是否可以将AJAX POST数据用于PHP类中的构造函数值?

时间:2011-05-05 10:26:42

标签: php ajax class variables constructor

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

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

更新:代码示例

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

3 个答案:

答案 0 :(得分:1)

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

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

并且在JS AJAX调用中你必须提供post的数据,例如用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']
        }
    );
});

答案 1 :(得分:1)

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

答案 2 :(得分:0)

最后,我决定编写一个基本的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!!
    }
}

随意使用,修改,传递判断等,我希望这有助于某人! ;)