Home > Article > Backend Development > How to return data to the front desk in php
How PHP returns data to the front desk:
1. PHP connects to the database to obtain the database information and puts it into json_encode($css);{The file is: db.php }
Using the json_encode() built-in function in php (php > 5.2) can enable data in php to be transferred and used well with other languages.
<span style="font-size:14px;"><?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();</span>
2. Put the data of json_encode($css) in success: function(data), as follows: {baixing.html}
$.ajax({ type: 'POST', url: 'db.php', data:{ // "username":"admin", // "password":"123456" }, success: function (data) { var result=eval("("+data+")"); alert(result); for(var i=0;i<result.length;i++){ var str='<div class="home1">'+ '<img src="'+result[i][1]+'" alt="'+result[i][3]+'"/>'+ '<p><a href="'+result[i][2]+'">'+result[i][3]+'</a></p>'+ '<div class="price">'+ '<span>¥'+result[i][4]+'</span>'+ '<del>¥'+result[i][5]+'</del>'+ ' <a href="#">预定:<b>'+result[i][6]+'</b>件</a>' '</div> </div>' $(".box7 #hotSale").append(str);//追加到你需要放在的位置 } } });$.ajax({ type: 'POST', url: 'db.php', data:{ // "username":"admin", // "password":"123456" }, success: function (data) { var result=eval("("+data+")"); alert(result); for(var i=0;i<result.length;i++){ var str='<div class="home1">'+ '<img src="'+result[i][1]+'" alt="'+result[i][3]+'"/>'+ '<p><a href="'+result[i][2]+'">'+result[i][3]+'</a></p>'+ '<div class="price">'+ '<span>¥'+result[i][4]+'</span>'+ '<del>¥'+result[i][5]+'</del>'+ ' <a href="#">预定:<b>'+result[i][6]+'</b>件</a>' '</div> </div>' $(".box7 #hotSale").append(str); } } });
Recommended: php server
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!