Blogger Information
Blog 29
fans 0
comment 0
visits 11070
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
1. 实现用户注销 2. 封装表单字段的原生验证方法 3. 定界符heredoc, nowdoc的用法与使用
尹辉
Original
609 people have browsed it

一,web1 项目实现用户注销

1)header.php 中,给菜单添加注销按钮,并添加 onclick 事件

  1. <?php if (isset($_SESSION['user']['name'])): ?>
  2. <a href="javascript:;" onclick="logout()">
  3. <?= $_SESSION['user']['name'] . '注销' ?>
  4. </a>
  5. <?php else: ?>
  6. <a href="login.php">登录</a>
  7. <?php endif; ?>

2)onclick 事件的执行函数 logout(),异步请求 logout.php

  1. async function logout() {
  2. if (confirm('是否退出?')){
  3. const url = './lib/user/logout.php';
  4. const response = await fetch(url);
  5. const result = await response.json();
  6. if (result){
  7. alert('退出成功!');
  8. location.href = 'index.php';
  9. } else {
  10. alert('系统错误,请重试。');
  11. location.href = 'login.php';
  12. }
  13. }
  14. }

3)logout.php

  1. session_start();
  2. $flag = false;
  3. // 执行 session_destroy(),成功返回 true
  4. if (session_destroy()){
  5. $flag = true;
  6. }
  7. echo json_encode($flag);

二,封装表单字段的原生验证方法

register.php 中添加 JavaScript 脚本,自定义 getInput(form) 函数,获取并返回用户输入内容:

  1. const getInput = (form) => {
  2. return {
  3. nickname: {
  4. ele: form.nickname,
  5. value: form.nickname.value.trim()
  6. },
  7. email: {
  8. ele: form.email,
  9. value: form.email.value.trim()
  10. },
  11. password: {
  12. ele: form.password,
  13. value: form.password.value.trim()
  14. },
  15. rePassword: {
  16. ele: form.rePassword,
  17. value: form.rePassword.value.trim()
  18. }
  19. }
  20. }

三,定界符heredoc, nowdoc的用法与使用

定界符,存放长字符串,格式:<<< 开始名称 字符串 结束名称

  1. heredoc,开始名称不加引号,解析变量和特殊字符(如转义符)

    1. $str = <<< POEM
    2. 窗前明月光,\n疑是地上霜。\n
    3. POEM;
    4. echo $str;
    5. // 输出:
    6. // 窗前明月光,
    7. // 疑是地上霜。
  2. nowdoc,开始名称加引号,不解析变量和特殊字符(如转义符)

    1. $str = <<< 'POEM'
    2. 窗前明月光,\n疑是地上霜。\n
    3. POEM;
    4. echo $str;
    5. // 输出:
    6. // 窗前明月光,\n疑是地上霜。\n

注意:结束名称前不能有任何字符(包括空格),否则会出错。

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post