PHP-AJAX接口(PostgreSQL)

api.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 == 'testSql'){
     
      echo $main -> testSql();
    }
?>

main.php


//header('Content-Type: text/html;charset=utf-8');
class Main{
     
	//json
	public function json($code,$message,$data=array()){
       
        $result=array(  
            'code'=>$code,  
            'message'=>$message,  
            'data'=>$data   
        );  
        //输出json  
        echo json_encode($result);  
        exit;  
	}	
    // 配置数据库连接
    public function conn(){
     
		$host    = "host=127.0.0.1";
		$dbname   = "dbname=postgres";
		$credentials = "user=postgres password=you-may-3701";
		$conn = pg_connect( "$host $dbname $credentials" );
        return $conn;
    }
		
    // 测试数据库查询
    public function testSql(){
     
		$dataarr = array();  
		// 定义数据库连接
		$conn = $this -> conn();
		$sql =<<<EOF
			SELECT * from faqdata order by id desc limit 10;
EOF;
		$ret = pg_query($conn, $sql);		
		// 遍历结果成数组
		if(!$ret){
     
			echo pg_last_error($conn);
			exit;
		}
		while($row = pg_fetch_row($ret)){
     
			$dataarr[]=$row;
		}
		pg_close($conn);
		return $this -> json(200,"数据返回成功",$dataarr);	
    }
}
?>

index.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 type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js">script>
	<script type="text/javascript">
        $.ajax({
      
            url: 'api.php?type=testSql',
            type: 'post',
            dataType: 'JSON',
            success: function (data) {
      
				$("#test").html(data.data[0].ImportTime)
                console.log(data);
            },
            error: function(err) {
      
                console.log(err)
            }
        });
    script>
head>
<body>
	<div id="test">

	div>
body>
html>

你可能感兴趣的:(PHP)