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 ) ;
}
}
} ) ;
سأكتب وثائق أكثر تفصيلا قريبا.