Home  >  Article  >  Backend Development  >  How to return data to the front desk in PHP

How to return data to the front desk in PHP

angryTom
angryTomOriginal
2019-10-16 14:51:538771browse

How to return data to the front desk in PHP

How does PHP return a data to the front desk

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 &#39;UTF8&#39;");
$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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn