AjaxHandler
1.0.0
switch
снова.Вы устали снова и снова писать один и тот же код обработчика Ajax для каждого проекта? Всегда есть одни и те же шаги и одни и те же проблемы. Правильно ли обрабатываются заголовки? Будет ли это работать с jQuery? Коды статуса? JSONP?
Что ж, я собрал все фрагменты кода вместе и создал AjaxHandler. Это очень простой класс PHP, который вы можете наследовать и легко создавать свои собственные обработчики Ajax.
Вот список функций, которые предоставляет Ajax Handler.
json_encode
при выводе.Вот очень простой пример использования AjaxHandler, скажем, это person.php.
<?php
include " AjaxHandler.php " ;
class Person extends AjaxHandler{
/**
* Private function will not be accessed from outside
* @return Mongo Collection
*/
private function getMongo (){
$ m = new Mongo ();
$ db = $ m -> selectDB ( ' main ' );
$ cl = $ db -> selectCollection ( ' people ' );
return $ cl ;
}
/**
* All I write here is the code
* I didn't write anything to handle output
* If the code gives an exception, ajax
* handler will return error, If Everything is successfull
* Standart success message will be returned
* @return [type] [description]
*/
public function createPerson (){
$ db = $ this -> getMongo ();
$ result = $ cl -> save ( array (
" name " => $ this -> get ( ' name ' ),
" age " => $ this -> get ( ' age ' )
));
}
/**
* Here is the code for handling your own messages
* @return [type] [description]
*/
public function getPersonDetails (){
$ db = $ this -> getMongo ();
$ cursor = $ db -> fetch ( array ( ' name ' => $ this -> get ( ' name ' )));
if ( $ cursor -> count () === 0 ){
// Will produce an error
// {"success": false, "error": "Person cannot be found"}
$ this -> error ( ' Person cannot be found ' );
} else {
// Will giveout a JSON success message
// {
// "success": true,
// "details":{"name":"john", "age":"29"},
// "message":"Operation successful"
// }
$ this -> success ( array (
" details " => $ cursor -> first ()
));
}
}
}
?>
Вы можете легко делать запросы с помощью jQuery.
$ . ajax ( {
url : 'person.php' ,
data : {
action : 'createPerson' ,
name : 'john' ,
age : 29
} ,
dataType : 'json' ,
complete : function ( res ) {
if ( res . success ) {
alert ( 'User Saved' ) ;
} else {
alert ( 'Error: ' + res . error ) ;
}
}
} ) ;
Скоро напишу более подробную документацию.