AjaxHandler
1.0.0
switch
itu lagi.Apakah Anda lelah menulis kode handler Ajax yang sama berulang kali di setiap proyek Anda? Selalu ada langkah yang sama dan masalah yang sama, apakah header ditangani dengan benar? Apakah ini akan berfungsi dengan jQuery? Kode Status? JSONP?
Baiklah, saya telah mengumpulkan semua potongan kode dan membuat AjaxHandler. Ini adalah Kelas PHP yang sangat sederhana yang dapat Anda warisi dan buat penangan Ajax Anda sendiri dengan mudah.
Berikut adalah daftar fitur yang disediakan Ajax Handler
json_encode
saat mengeluarkan.Berikut adalah contoh paling mendasar dari AjaxHandler yang digunakan, katakanlah ini 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 ()
));
}
}
}
?>
Anda dapat membuat permintaan dengan jQuery dengan mudah
$ . 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 ) ;
}
}
} ) ;
Saya akan segera menulis dokumentasi yang lebih rinci.