Home >Backend Development >PHP Problem >How to return data to the front desk in PHP
1. The front end requests the background interface to obtain data through ajax.
Note: The jQuery.js library needs to be introduced before this code.
$.ajax({ type: 'POST', url: 'db.php', data:{ }, success: function (data) { alert(data); } } });
2. The background After php query, it is converted into json data format through json_encode() and returned to the front end
<?php $host="localhost"; $username="root"; $password="root"; $dbName="baixing"; $port=3306; $conn=new mysqli($host,$username,$password,$dbName,$port); if(!$conn){ die("error:".$conn->connect_error); } //设置查询结果的编码,一定要放在query之前 $conn->query("SET NAMES 'UTF8'"); $result=$conn->query("select * from hotgoods"); //$conn->query()获取的是二进制 //将查询的结果集封装到一个数组里 $css=$result->fetch_all(); //以json的格式发送ajax的success中由data接收 echo json_encode($css); $conn->close();
For more PHP related knowledge, please visit PHP Chinese website!
The above is the detailed content of How to return data to the front desk in PHP. For more information, please follow other related articles on the PHP Chinese website!