这是客户端的代码:
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'server.php',
type: 'POST',
timeout: 30000,
error: function(){
alert('请求出错');
},
success: function(msg){
alert(msg);
}
});
});
});
</script>
服务端代码:
<?php
$user = $_POST['username'];
$pass = $_POST['password'];
//连接数据库
mysql_connect('xxx','xxx','xxx') or die("数据库连接失败");
//设置编码
mysql_query('set names utf8');
//选择数据库
mysql_query("USE upin");
$res = mysql_query("SELECT * FROM upin_production_area");
$rows = array();
//获取结果集
while($row = mysql_fetch_array($res)){
$rows[] = $row;
}
//json编码
echo json_encode($rows);
我只知道大概是这个原理,不知道具体怎么做规范,求教!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
RESTful API 设计指南[阮一峰]
http://www.ruanyifeng.com/blog/2014/05/restful_api.html
现在最普遍的就是restful 当然也不一定要按照这个标准来实现,其实最简单的可以实现功能,内部定好接口的格式就可以了
如果在实际开发中
1.响应类response.class,其中包含不同请求方式的处理,需要至少三个变量,$code状态码,$message信息提示,$data处理数据,一个返回值json或者xml
2.单例模式数据库类db.class封装,数据库的操作都放在里面
3.需要一个app接口文档
具体你可以参考慕课网上有一个php app接口的课程,很全面