html+ajax+PHP+mysql实现数据展示在前端页面
html+ajax+PHP+mysql实现数据展示在前端页面
经过一段学习,通过百度资源和查看了各个大佬博客内容,终于实现这个功能,顺便记录一下! 文中不足请多指正!
环境介绍:
Mac OS 10.15 homebrew 安装的PHP 7.3 自带Apache 2.4.39 mysql 5.7
话不多说直入正题 前端html: index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="js/jquery-3.4.1.min.js"></script> <title>Showinfo</title> </head> <body> <p id="user" style="font-size: 19px;"></p> <p >个人简介:<span id="introduction" style="color: darkblue"></span></p> </body> </html>
ajax部分:
//昵称简介展示 $.ajax({ url:php/nick.php, //获取URL地址 dataType:json, //返回json type:post, success:function (msg) { //接受成功则执行以下操作 var str="<span>"; var str2="<span>"; $.each(msg,function(i,n){ //$.each()是对数组,json的遍历 。第一个参数表示遍历的数组的下标,第二个参数表示下标对应的值 str+="<span>"+""+n.nickname+"</span>"; str2+="<span>"+""+n.introduction+"</span>"; }); str+="</span>"; str2+="</span>" $("#user").append(str); //将从后台数组获取到的值放在id为 user的元素中 $("#introduction").append(str2); } })
PHP部分: nick.php
<?php session_start(); $uid=$_SESSION[uid]; //读取之前存入的session记录 $conn=mysqli_connect(127.0.0.1,root,1234,hopeless); //连接数据库,url地址,数据库用户,数据库密码,数据库名 $sql="select nickname,introduction from userinfo where uid=$_SESSION[uid]"; //从数据库中查询昵称 mysqli_set_charset($conn,utf8mb4); $res=mysqli_query($conn,$sql); $dataarray=array(); if($rows=mysqli_fetch_assoc($res)){ //遍历数据库 array_push($dataarray,$rows); } $data=json_encode($dataarray); //json编码解析 print_r($data); //print_r($arrry) 输出数组 mysqli_close($conn); ?>
还有许多不足需要进行改正,会继续努力。 最近碰到的一个问题是:运行PHP时会一直处于 “正在等待localhost” ,不知道该怎么解决…真是让人头痛 感谢阅读!!