PHP-AJAX接口(SQLServer)

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 == 'test'){
     
      echo $main -> test();
    }
    elseif($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(){
     
		$serverName = "数据库ip地址";
		$connectionOption = array(
        "Database" => "数据库名",
        "Uid" => "账号",
        "PWD" => "密码"
		);
		$conn = sqlsrv_connect($serverName,$connectionOption);	
        return $conn;
    }
	
    // 测试接口
    public function test(){
     
		$a = $_POST['a'];
		return json_encode(array('error' => 200, 'msg' => '接口连接成功','a'=>$a));     
    }
	
    // 测试数据库查询
    public function testSql(){
     
		$dataarr = array();  
		// 定义数据库连接
		$conn = $this -> conn();
		// 建立数据库查询语句
		$tsql = "SELECT * from T_Settings;"; 
		// 执行数据库查询语句(返回查询结果)
		$getResults = sqlsrv_query($conn,$tsql);
		// 遍历结果成数组
		if(!$getResults) {
     
			return json(444,"无数据");
		} else {
     
			while($row = sqlsrv_fetch_array($getResults,SQLSRV_FETCH_ASSOC)) {
     
				$dataarr[]=$row;  
			}  
			// 输出查询结果
			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=test',
            type: 'post',
            data: {
      
                a: '123'
            },
            dataType: 'JSON',
            success: function (data) {
      
                console.log(data);
            }
        });
        $.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)