可爱熊个人博客

php写app接口并返回json数据

第一步:conn.php文件,用于连接数据库并定义接口格式,代码如下:

<?php
header(“charset=utf-8″);
$servername=”localhost”;
$username=”root”;
$password=”root”;
$dbname=”test”;
$conn = mysql_connect($servername,$username,$password);
if(!$conn){
echo “数据库连接失败!”;
}
mysql_select_db($dbname);
class Response{
public static function json($code,$message=””,$data=array()){
$result=array(
‘code’=>$code,
‘message’=>$message,
‘data’=>$data
);
//输出json
echo json_encode($result);
exit;
}
}

?>

第二步:text.php,用于将数据库中的数据转化为json字符串,并输出:

<?php
require_once(‘conn.php’);
/*
*选择数据表
* */
$sqla = “SELECT * from user”;
$result = mysql_query($sqla,$conn);
$dataarr = array();
while($row = mysql_fetch_array($result)){
$dataarr[]=$row;
}
$id=$_GET[‘id’];
if($id==1){
Response::json(1,’数据返回成功’,$dataarr);
}else if($id==2){
Message::json(0,’失败’);
}

?>

第三步:text.html,ajax加载json数据并显示:

<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title></title>
<script src=”http://libs.baidu.com/jquery/2.0.0/jquery.min.js”></script>
</head>
<body>
<input id=”text” type=”text”/>
<input type=”button” id=”tijiao” value=”提交” />
<div id=”tex”></div>
<script type=”text/javascript”>
$(“#tijiao”).click(function(){
var data={“id”:$(“#text”).val()}
$.get(“text.php?flag=showmessage”,data,function(res){
res=JSON.parse(res);//<span style=”color:#cc0000;”>将json字符串转化为json对象</span>
if(res.code==1){
$(“#tex”).empty();
$.each(res.data, function(x,y) {
$(“#tex”).append(“id:”+y.id+”/姓名:”+y.username+”<br>”);
});
}
})
})

</script>
</body>
</html>
———————
作者:包子源
来源:CSDN
原文:https://blog.csdn.net/ziwoods/article/details/53102574

 

Comments are closed.