AjaxHandler
1.0.0
switch
다시 쓰지 마세요.각 프로젝트에서 동일한 Ajax 핸들러 코드를 반복해서 작성하는 데 지치셨나요? 항상 같은 단계, 같은 문제가 있는데, 헤더를 올바르게 처리하고 있나요? jQuery와 함께 작동합니까? 상태 코드? JSONP?
글쎄, 나는 모든 코드 조각을 모아서 AjaxHandler를 만들었습니다. 이는 자신만의 Ajax 핸들러를 쉽게 상속하고 생성할 수 있는 매우 간단한 PHP 클래스입니다.
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 ) ;
}
}
} ) ;
조만간 더 자세한 문서를 작성하겠습니다.