开发者

Standard practise for ajax request page output?

开发者 https://www.devze.com 2023-03-10 15:16 出处:网络
What is the standard practise with PHP pages that are used for Ajax requests? Should they print out a single value (ex: get points of player with id = x)? Does/should a single page serve multiple requ

What is the standard practise with PHP pages that are used for Ajax requests? Should they print out a single value (ex: get points of player with id = x)? Does/should a single page serve multiple requests? If so, how can code be grouped on the PHP side?

P.S: An additional question: If a templating system like Smarty is used, would it be more开发者_如何学Go interesting security-wise to call the PHP page being used instead of calling the request page directly?


I think it makes sense to create arrays in php, then convert them to JSON and send back as a JSON object. This allows for more flexible manipulation of data both server and client side.


I use this piece of code in Javascript. Backend wise things are organized in a MVC type of organisation, so things affecting one module are usually grouped together. In general I also create a sperate module for a seperate model, but in some cases you may deviate from this principle.

PHP

Execute a piece of code and wrap it inside a try/catch block. This way error messages may be propagated to the frontend. This method helps in that regard to convert exceptions to a readable error. (to debug from json).

try {
    //... execute code ..  go about your buisness..
    $this->result = "Moved  " . count($files) . " files ";
    // result can be anything that can be serialized by json_encode()
} catch (Exception $e) {
   $this->error = $e->getMessage() . ' l: '  . $e->getLine() . ' f:' . $e->getFile();
   // return an error message if there is an exception. Also throw exceptions yourself to make your life easier.
}
// json response basically does something like echo json_encode(array("error" => $this->error, "result" => $this->result))
return $this->jsonResponse();

For error handling I often use this to parse errors.

public function parseException($e) {
    $result = 'Exception: "';
    $result .= $e->getMessage();
    $trace = $e->getTrace();
    foreach (range(0, 10) as $i) {
        $result .= '" @ ';
        if (!isset($trace[$i])) {
            break;
        }
        if (isset($trace[$i]['class'])) {
            $result .= $trace[$i]['class'];
            $result .= '->';
        }
        $result .= $trace[$i]['function'];
        $result .= '(); ';
        $result .= $e->getFile() . ':' . $e->getLine() . "\n\n";
    }

    return $result;
}

Javascript side

/**
 * doRequest in an ajax development tool to quickly execute data posts.
 * @requires jQuery.log
 * @param action (string): url for the action to be called. in config.action the prefix for the url can be set
 * @param data (object): data to be send. eg. {'id':5, 'attr':'value'}
 * @param successCallback (function): callback function to be executed when response is success
 * @param errorCallback (function): callback function to be executed when response is success
 */
jQuery.doRequest = function (action, data, successCallback, errorCallback) {
    if (typeof(successCallback) == "undefined") {
        successCallback = function(){};
    } 
    if (typeof(errorCallback) == "undefined") {
        errorCallback = function(data ){
            alert(data.error);
        };
    }
    jQuery.log(action);

    jQuery.post(action, data, function (data, status)
    {

        jQuery.log(data);
        jQuery.log(status);
        if (data.error !== null || status != 'success') {
            // error handler
            errorCallback(data);
        } else {
            successCallback(data);
        }
    },'json');
};

Note: the error callbacks are very nice if you combine them with something like pNotify

0

精彩评论

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