前端学PHP,ajax

php,又称超文本预处理器,是在服务器端执行的脚本语言, Hypertext Preprocessor。

访问过服务器的标志:访问的时候要有协议(http)。协议,网络协议的简称,网络协议是通信计算机双方必须共同遵从的一组约定。
网址组成:协议 - 域名 - 路径 - 数据 - 锚点 - 端口号(被浏览器省略了)
https(协议)://www.jianshu.com(域名)/u/a.html(路径)?a=1&b=2(数据)#top(锚点) :80(端口号),
此路径不存在,我自己编的,嘻嘻~~~,为了效果(懒得找).
自己电脑上也可以使用软件来模拟服务器,网上提供了很多这样的软件,我选用phpstudy。这个软件中集成了Apache服务器、MySql数据库和PHP编译器。每个服务要运行起来,都需要开启服务。Apache和MySql都需要开启。php编译器不需要,因为他不是一个服务。
phpstudy安装的时候,安装路径不能有中文汉字和空格字符。 强烈建议直接放在某个盘下,


自己访问自己:localhost 或者 127.0.0.1 或者本机IP地址 -- 代表WWW文件夹

  1. 使用http访问文件,都要放在WWW的文件夹中
  2. 提前开启phpstudy,否则访问不到
  3. 文件名和文件夹名不允许出现空格和中文
  4. 访问文件,必须使用域名或者ip地址
    文件后缀是php,其中的代码放在一个结构中:<?php开头 ,?>结尾,每行结束必须有;
    注释和js中使用一致。

设置phpstudy拥有目录列表
打开phpStudy - 其他选项菜单 - phpStudy设置 - 允许目录列表



效果:


返回上一级目录

js 连接php

1.form表单直接连接:<form action="路径 " method="post/get"></form>
<form action="../login.php" method="post"></form>
2. 创建ajax 连接PHP,客户端向服务器发起请求(Request)

ajax 异步的js和xml,async javascript and xml
作用:在不刷新页面的情况,发送http请求
(1)设置get请求连接

// 1.创建ajax对象 - 创建一部电话
var xhr = new XMLHttpRequest();
// console.log(xhr);
// 2.打开连接 - 拿起电话,点击号码
xhr.open('get','demo.php?id=1',true); // 第三个参数是布尔值,表示是否异步,发送的数据在?后
// 3.发送请求
xhr.send();

// 发送请求的时候可以携带数据 - 以字符串的形式发送
// xhr.send();
// 4.监听请求状态 - 等待接听
xhr.onreadystatechange = function(){
    // 判断xhr的状态(0~4  4的时候就圆满完成)和请求的状态 - 200
    if(xhr.readyState===4 && xhr.status==200){
        // 接收响应数据
        let res = xhr.responseText;
        // console.log(res);
        console.log(456);
  }
}

(2)设置post请求连接

    var xhr = new XMLHttpRequest();
    xhr.open("post","../login.php");
    xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
    xhr.send(`username=${username}&password=${password}`);
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
            var res = xhr.responseText;
            res = JSON.parse(res);
            // console.log(res);
            if(res.meta.status===201){
                alert(res.meta.msg);
                location.href = "home.html";
            }else{
                alert(res.meta.msg);
                return false;
            }
        }
    }

PHP接收js传送数据,,服务器向客户端发起相应(Reponse)

user-agent: Mozilla/5.0 # 产生请求的浏览器信息
accept: application/json # 表示客户端希望接受的数据类型
Content-Type: application/x-www-form-urlencoded # 客户端发送的实体数据格式
Host: 127.0.0.1 # 请求的主机名(IP)
常见的请求方式:

  1. GET: 查
  2. POST: 增
  3. PUT: 改
  4. DELETE: 删

GET和POST的区别

  1. get请求的数据会显示在地址栏,post的数据不显示
  2. get请求的数据大小有限制:
    • IE: 2083 个字符
    • FireFox: 65536 个字符
    • Safari: 80000 个字符
    • Opera: 190000 个字符
    • Chrome: 8182 个字符
      post请求的数据没有限制,除非服务器主动设置。
  3. get请求的数据类型必须是ASCII,post没有限制
  4. get相对不安全,post相对安全
    get请求接收数据,GET 请求是没有请求体数据的
<?php
header("content-type:text/html;charset=utf8");
// 接收传过来的省份id
$id = $_GET["id"];
$con = mysqli_connect("localhost","root","root","test");
mysqli_query($con,"set names utf8");
$res = mysqli_query($con,"select * from region where pid=$id");
$arr = [];
while($row = mysqli_fetch_assoc($res)){
    $arr[] = $row;
}
echo json_encode($arr);

post 请求接收数据,POST 请求有请求体数据

header("content-type:text/html;charset=utf8");
// 接收数据
// var_dump($_POST);
$username = $_POST["username"];
$password = $_POST["password"];

// var_dump($username,$password);

$con = mysqli_connect("localhost","root","root","test");
$sql = "select * from user where username='$username'";
$res = mysqli_query($con,$sql);
// 从中提取一条数据来验证
$row = mysqli_fetch_assoc($res);
if($row){
    // 用户名存在
    // 验证密码是否正确
        echo '<script>
            alert("登陆成功");
            location.href = "home.html";
        </script>';
    }

php输出方式

echo 1; // 文本方式输出,输出基本类型
echo("6");
var_dump(1); // int(1) ;基本类型和复杂类型都能输出;类似于console.log 程序员用
header("content-type:text/html;charset=utf8");  // 设置编码 中文会乱码
print("世界你好");  // 输出简单类型
print_r("PHP你好");  // 可输出复杂类型

变量

使用$来定义变量

$a = 10;

字符串
单引号只能输出纯字符串,双引号可以输出变量

$a = 5;  
echo("$a");  // 5
echo '$a';  // $a

数组:

$arr = [
    "name"=>"张三",
    "age"=>"12"
];
$brr = [3,"57","9"];
var_dump($arr);  // array(2) { ["name"]=> string(6) "张三" ["age"]=> string(2) "12" } 每个汉字占三个字符串
var_dump($brr);  // array(3) { [0]=> int(3) [1]=> string(2) "57" [2]=> string(1) "9" }
// 遍历
$arr = [
    "name"=>"张三是大众人物",
    "age"=>"12"
];
foreach($arr as $a){  // 遍历值
    echo "$a";    
};   // 张三是大众人物12
foreach($arr as $c => $b){  // 遍历键值
    echo "$c - $b";
};  // name - 张三是大众人物age - 12
$str = json_encode($brr); // 将数组转为字符串
echo $str;  // {"name":"\u5f20\u4e09\u662f\u5927\u4f17\u4eba\u7269","age":"12"}
$crr = json_decode($str,true);  // json字符串转化为数组
var_dump($crr);  // array(2) { ["name"]=> string(21) "张三是大众人物" ["age"]=> string(2) "12" }

字符串拼接

$e = 5 . 90;$a = "6" . 90;echo $a,$e; // 690590
echo("<meta charset='utf-8'>");  // 可定义字符串引用类型,但作为数据,不推荐
echo "<b>你好世界";  // 你好世界 加粗这里都是单标签引用
<?php
// echo '<b>hello world</b>';
// echo '<meta charset="utf-8">';
header("content-type:text/html;charset=utf8");
// echo '你好世界';

// 连接数据库
// 1.创建连接
$con = mysqli_connect('localhost','root','root','test');
// // var_dump($con);
// // 2.执行增删改查的命令语句
$res = mysqli_query($con,'select * from personInfo');
echo '<pre>';   // 变得容易看一点
var_dump($res);
// 3.从这个结果拿出能看懂的数据 - 从结果中拿出第一条数据
$row = mysqli_fetch_assoc($res);
$row1 = mysqli_fetch_assoc($res);
$row2 = mysqli_fetch_assoc($res);
$row3 = mysqli_fetch_assoc($res);
echo "<pre>";
print_r($row);

$arr = [];
while($row = mysqli_fetch_assoc($res)){
    $arr[] = $row;
}
echo '<pre>';
print_r($arr);

/*
查询:
    1.连接数据库
        连接 = mysqli_connect(主机名,用户名,密码,要连接数据库名称)
        连接成功返回一个object,连接失败返回false
    2.执行命令语句
        结果 = mysqli_query(连接,字符串命令语句)
        查询成功返回object,查询失败了false
    3.从结果中提取数据
        一行数据 = mysqli_fetch_assoc(结果) - 最终的数据是一个数组
*/

// 增
// 1.连接数据库
$con = mysqli_connect("localhost","root","root","test");
// 2.执行命令语句
$res = mysqli_query($con,"insert personInfo(name,age,aid) values('吴九',19,3)");
// 执行增、删、改的语句,执行结束的结果是一个布尔值,成功为true,失败为false
if($res){
    echo '成功';
}else{
    echo '失败';
}


// 改
// 1.连接数据库
$con = mysqli_connect("localhost","root","root","test");
// 2.执行语句
$res = mysqli_query($con,"update personInfo set name='周扒皮' where id=6");
if($res){
    echo '成功';
}else{
    echo '失败';
}


// 删
$con = mysqli_connect("localhost","root","root","test");
// $res = mysqli_query($con,"delete from personInfo where id=8");
$res = mysqli_query($con,"delete from personInfo");
if($res){
    echo '成功';
}else{
    echo '失败';
}

为了(提高逼格)更容易看,通常情况下响应的数据格式:

{
    meta:{
        status:状态码,
        msg:"提示信息"
    },
    data:null
}

直接用这个格式替换echo "失败";

if($res){
        // 注册成功
        $arr = [
            "meta"=>[
                "status"=>201,
                "msg"=>"注册成功"
            ],
            "data"=>null
        ];
    }else{
        // 注册失败
        $arr = [
            "meta"=>[
                "status"=>301,
                "msg"=>"注册失败"
            ],
            "data"=>null
        ];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。