前不久有一问题困扰着我,把一个项目的前后端完全分离后,它们之间的数据是如何交互的,百度了一翻,得出的结论:在后端把数据封装成json的格式,再返回到前端由js将其转换成json格式,再解释出来,渲染到页面上,原来如此!废话不多说,直接上代码
如有不妥之处,请给予指正
先来前端的
<<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>前后端分离</title>
</head>
<body>
<input type="button" value="获取数据" onclick="getdata()">
<script type="text/javascript">
function getdata(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
eval("backdata="+xhr.responseText);
xuanran(backdata.json);
console.log(backdata);
}
};
xhr.open('get','./text.php');
xhr.send(null);
}
function xuanran(data){
for(x in data){
for(y in data[x]){
document.write(data[x][y]);
}
}
}
</script>
</body>
</html>
后端的
<?php
header('content-type:text/json');
selectXiBu();
function selectXiBu(){
$connection = mysqli_connect("localhost","root","","php");
if(!$connection){
echo "数据库连接错误";
}
else{
mysqli_query($connection,'set names utf8');
$selectSql = "select * from student limit 50";
$result = mysqli_query($connection,$selectSql);
$count=0;
$aaaa="";
$json="";
while ($row = mysqli_fetch_array($result)){
$count++;
$xh = $row['student'].$row['学号'];
$xm = $row['student'].$row['姓名'];
$sex = $row['student'].$row['性别'];
$nl = $row['student'].$row['年龄'];
$dh = $row['student'].$row['电话'];
$xb = $row['student'].$row['系部'];
$zy = $row['student'].$row['专业'];
$dz = $row['student'].$row['地址'];
$key="s".$count;
$value="\"学号\":\"$xh\",\"姓名\":\"$xm\",\"性别\":\"$sex\",\"年龄\":\"$nl\",\"电话\":\"$dh\",\"系部\":\"$xb\",\"专业\":\"$zy\",\"地址\":\"$dz\"";
$aaaa.="\"".$key."\"".":"."{".$value."}".($count<50?",":"");
$json ="{\""."json"."\"".":{".$aaaa."}}";
}
echo $json;
}
}
?>