您可以使用这些东西来实现这些功能。
- 基于 PHP JSON 的 API
- 基于 PHP 套接字的 JSON API
- 基于套接字 IO 的 API
所有这些 API 都可以很容易地被 AngularJS 或 jQuery 解析
对于 PHP,如何制作 API
<?php
//Set header for Javascript to recognize it as the JSON output
header('Content-Type:application/json;');
//I am using GET parameters, but POST can also be used and can make amazing APIs
switch($_GET['action']){
case "addlike":
//SQL Query passed to add a like as facebook
//Set the output array to provide json Output, here's the example
$output['status'] = 200;
$output['message'] = 'Like Added';
break;
case "addcomment":
break;
}
echo json_encode($output);
要使用上面的代码,URL 应该是:
http://yourserve/youfile.php/?action=addlike
输出将是
{
"status":200,
"message":"Like Added"
}
如何在 jQuery 中使用它
/** For Example you have like button with class="btnlike" **/
$('.btnlike').on('click',function(){
$.get('http://yourserve/youfile.php',{action:'addlike'},function(data){
if(data['status'] == 200){ alert('You Liked the Post'); }
});
});
如何在 AngularJS 中使用
app.controller('myCtrl',function($scope,$http){
$scope.message = '';
$scope.addlike = function(){
$http.get('http://yourserve/youfile.php',{action:"addlike"}).success(function(data){
if(data['status']==200){ $scope.messages = 'You liked the post'; }
});
};
});