AjaxHandler
1.0.0
switch
再度書かないでください。各プロジェクトで同じ Ajax ハンドラー コードを何度も書くことにうんざりしていませんか?常に同じ手順と同じ問題が発生します。ヘッダーは正しく処理されていますか? jQueryでも動作するのでしょうか?ステータスコード? JSONP?
さて、すべてのコード部分を集めて AjaxHandler を作成しました。これは非常に単純な PHP クラスであり、独自の Ajax ハンドラーを簡単に継承して作成できます。
Ajax ハンドラーが提供する機能のリストは次のとおりです。
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 ) ;
}
}
} ) ;
近いうちにさらに詳細なドキュメントを書きます。