PHP-AJAXインタフェース(PostgreSQL)

18339 ワード

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>