PHP学习(一)基础api

168 阅读1分钟

基础部分

声明变量、块级作用域

...
<body>
<?php

if (isset($a)) {
    echo "我声明了";
} else {
    echo "我没声明"; // true
}

$a = 50;
echo $a; // 50
function test()
{
    global $a;
    echo $a; // 不加上面那行会报错
}

test();
?>
</body>
...

引入文件

./index.php
<?php
//require_once "./global.php"; 
include_once "./global.php";
echo $GLOBALS["hello"]; // hello php
?>
···
./global.php

<?php
$GLOBALS["hello"]="hello php";
?>

include 的文件中出错了,主程序继续往下执行,require 的文件出错了,主程序也停了,所以包含的文件出错对系统影响不大的话(如界面文件)就用 include,否则用 require。

数组

$arr = array('0' => "苹果", '1' => "测试");
echo $arr[0]; // 苹果

session 会话机制

./index.php
session_start();
$_SESSION['views']=1;
···
./a.php
session_start();
$_SESSION['views']=1;
echo $_SESSION['views']; // 1

表单请求

./index.php

<form action="./a.php" method="get">
    用户名:<input type="text" name="username">
    密码:<input type="password" name="password">
    <input type="submit" value="提交">
</form>
···
<?php
header("Content-type:text/html;charset=utf-8");
$username = $_GET['username'];
//$username = $_REQUEST['username'];
//$username = $_POST['username'];
if ($username == "admin") {
    echo $_GET['password'];
} else {
    echo '不是admin';
}
?>

ajax 请求

./index.php

用户名:<input type="text" id="username" >
密码:<input type="password" id="password" >
<input id="btn" type="submit" value="提交">
    
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script>
    $("#btn").click((ev) => {
        ev.preventDefault();
        $.ajax({
            url: "a.php",
            type: "get",
            dataType: "json",
            data: {
                username: $('#username').val(),
                password: $('#password').val(),
            },
            success: data => {
                console.log(data);
            },
            error: err => {
                console.log(err);
            }
        })
    });
</script>
...
./a.php

<?php
$username = $_GET['username'];
//$username = $_REQUEST['username'];
//$username = $_POST['username'];
if ($username == "admin") {
    echo json_encode(array('msg' => '登陆成功', 'errCode' => 'yes'),JSON_UNESCAPED_UNICODE);
} else {
    echo json_encode(array('msg' => '登陆失败', 'errCode' => 'no'),JSON_UNESCAPED_UNICODE);
}
?>