zoukankan      html  css  js  c++  java
  • 使用PHP写ajax接口

    使用PHP写ajax接口

    之前有学过php都是前后端没有分离的,所以也想去了解后端是怎么写出ajax接口的,可能问了别人或者上网找了很多资料都很有有点懵,或者说直接用TP或者lavarel这些后端框架去写,有时候看到这么多东西或者涉及的文件越多,就容易越乱,所以就想找一种简单明白一点的方法。这样可以方便自己平时做一些涉及简单的CURD的小项目。

    有点简单,就两个文件:

    • main.php
      这个文件主要是用来写数据库连接的配置还有接口的逻辑。

    • api.php
      这个文件是用来管理所有接口还有访问响应的配置。

    例子

    在main.php里面配置好数据库连接,然后编写接口,示例:

    main.php

    <?php
    header('Content-Type: text/html;charset=utf-8');
    class Main{
        // 配置数据库连接
        public function conn(){
            // (主机,账号,密码,数据库,端口号)
            $conn = new mysqli('localhost','root', '123456','test');
            $conn->set_charset("utf8");
            // 检测连接 
            // if ($conn->connect_error) { die("数据库连接失败: " . $conn->connect_error); } echo "数据库连接成功";
            return $conn;
        }
        // 测试接口
        public function test(){
          $a = $_POST['a'];
            return json_encode(array('error' => 200, 'msg' => '接口连接成功','a'=>$a));
          }
        }
        // 测试数据库查询
        public function testSql(){
          // 获取post过来的data
          $id = $_POST['id'];
          // 判断是否传值
          if(!$id){
            return json_encode(array('error' => 500, 'msg' => '参数缺失'));
          }
          // 定义数据库连接
          $conn = $this -> conn();
          // 建立数据库查询语句
          $search = "SELECT * FROM `test` WHERE `id` = $id";
          // $search = "SELECT * FROM `test`";      
          // 执行数据库查询语句(返回查询结果)
          $result = $conn -> query($search);
          // 遍历结果成数组
          if(!$result) {
            return json_encode(array('error' => 444, 'msg' => '无数据'));
          } else {
            while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
              $arr[]=$row;
            }
            // 输出查询结果
            return json_encode(array('error' => 200, 'data' => $arr));
          }
        }
    }
    ?>
    

    在api.php中添加接口列表

    其实就是在接口连接使用?xxx=xxx这种方式发送一个参数,然后通过这个参数判断要请求的接口是哪一个
    api.php

    <?php
        header('Content-Type: text/html;charset=utf-8');
        // 指定允许其他域名访问
        header('Access-Control-Allow-Origin:*');
        // 响应类型  
        header('Access-Control-Allow-Methods:POST');
        // 响应头设置  
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        
        require_once('main.php');
         
        $type = @$_GET['type'];
        $main = new Main();
        if($type == 'test'){
          echo $main -> test();
        }
        elseif($type == 'testSql'){
          echo $main -> testSql();
        }
    ?>
    

    调用接口

    index.html

    <!DOCTYPE html>
    <html lang="zh">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>测试接口</title>
        <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
    </head>
    
    <body>
        <script>
            $.ajax({
                url: 'api.php?type=test',
                type: 'post',
                data: {
                    a: '123'
                },
                dataType: 'JSON',
                success: function (data) {
                    console.log(data);
                }
            });
            $.ajax({
                url: 'api.php?type=testSql',
                type: 'post',
                data: {
                    id: 1
                },
                dataType: 'JSON',
                success: function (data) {
                    console.log(data);
                },
                error: function(err) {
                    console.log(err)
                }
            });
        </script>
    </body>
    
    </html>
    
  • 相关阅读:
    HDU 5912 Fraction (模拟)
    CodeForces 722C Destroying Array (并查集)
    CodeForces 722B Verse Pattern (水题)
    CodeForces 722A Broken Clock (水题)
    CodeForces 723D Lakes in Berland (dfs搜索)
    CodeForces 723C Polycarp at the Radio (题意题+暴力)
    CodeForces 723B Text Document Analysis (水题模拟)
    CodeForces 723A The New Year: Meeting Friends (水题)
    hdu 1258
    hdu 2266 dfs+1258
  • 原文地址:https://www.cnblogs.com/chifung/p/9599655.html
Copyright © 2011-2022 走看看