博客列表 >ajax 表单的无刷新上传

ajax 表单的无刷新上传

王娇
王娇原创
2020年05月23日 22:03:03602浏览

学习总结

  • ajax可以实现表单无刷新上传,有较好的用户体验
  • ajax有两种上传方式,GET和POST,GET方式上传时,发送数据为空,POST方式时,发送数据为json字符串

1.登录界面无刷新上传

1.1首页 index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>Document</title>
  7. <link rel="stylesheet" href="css/index.css" />
  8. <script src="js/login.js"></script>
  9. </head>
  10. <body>
  11. <div class="login">
  12. <div class="title">
  13. <span>会员登录</span><span>(手机号码或者邮箱登录)</span>
  14. </div>
  15. <form action="" method="POST" onsubmit="return false">
  16. <input
  17. type="text"
  18. name="userName"
  19. id="userName"
  20. placeholder="example@163.com"
  21. required
  22. />
  23. <input
  24. type="password"
  25. name="passWord"
  26. id="passWord"
  27. placeholder="****"
  28. required
  29. />
  30. <div>
  31. <input
  32. type="text"
  33. name="captcha"
  34. id="captcha"
  35. placeholder="请输入验证码"
  36. require
  37. />
  38. <img src="" onclick="reFresh()" />
  39. <input
  40. type="hidden"
  41. name="relCaptcha"
  42. id="relCaptcha"
  43. class="relCaptcha"
  44. value=""
  45. />
  46. </div>
  47. <div class="button" onclick="checkLogin()">登录</div>
  48. <div id="showInfo"></div>
  49. </form>
  50. </div>
  51. </body>
  52. <script>
  53. reFresh();
  54. </script>
  55. </html>

1.2表单ajax处理login.js

  1. //------------------------
  2. //登录无刷新验证
  3. //---------------------------
  4. function checkLogin() {
  5. //获取form表单
  6. var form = document.querySelector("form");
  7. //创建ajax对象
  8. var xml = new XMLHttpRequest();
  9. //临听ajax异步对象
  10. xml.onreadystatechange = function () {
  11. if (xml.readyState == 4 && xml.status == 200) {
  12. var loginSta = JSON.parse(xml.responseText);
  13. var status = loginSta.status;
  14. var message = loginSta.message;
  15. console.log(status, message);
  16. document.getElementById("showInfo").innerText = message;
  17. if (status) {
  18. document.getElementById("showInfo").style.color = "green";
  19. } else {
  20. document.getElementById("showInfo").style.color = "red";
  21. }
  22. }
  23. };
  24. //初始化ajax对象
  25. xml.open("POST", "login.php", true);
  26. var data = new FormData(form);
  27. //发送数据
  28. xml.send(data);
  29. }
  30. //------------------------------
  31. //验证码无刷新显示
  32. //---------------------------------
  33. function reFresh() {
  34. //创建ajax对象
  35. var xml = new XMLHttpRequest();
  36. //临听ajax异步对象
  37. xml.onreadystatechange = function () {
  38. if (xml.readyState == 4 && xml.status == 200) {
  39. var data = JSON.parse(xml.responseText);
  40. var captcha = data.captcha;
  41. var relcapt = data.relcapt;
  42. document.querySelector("img").src = captcha;
  43. document.getElementById("relCaptcha").value = relcapt;
  44. }
  45. };
  46. //初始化ajax对象
  47. xml.open("GET", "captcha.php", true);
  48. //发送数据
  49. xml.send(null);
  50. }

1.3显示验证码captcha.php

  1. <?php
  2. namespace login;
  3. require_once 'vendor/autoload.php';//自动加载外部组件库
  4. use Gregwar\Captcha\CaptchaBuilder;//使用验证码的外部组件
  5. $builder = new CaptchaBuilder(4);//新建一个4位的验证码对象
  6. $builder->build();//生成一个4位验证码
  7. $captcha = $builder->inline();//生成一个图片文件,可以在img的src属性中使用
  8. $relcapt = strtolower($builder->getPhrase());//得到真实的4位验证码字符
  9. echo json_encode(['captcha'=>$captcha,'relcapt'=>$relcapt]);
  10. ?>

1.4处理登录验证 login.php

  1. <?php
  2. namespace login;
  3. session_start();
  4. require 'compotents/conn/DBconn.php';
  5. $user = new DBconn();
  6. $table = 'tb_user';
  7. $loginState = [];
  8. if($_SERVER['REQUEST_METHOD']==='POST'):
  9. $captcha = trim(strtolower($_POST['captcha']));
  10. $relcapt = $_POST['relCaptcha'];
  11. //判断验证码是否正确
  12. if($captcha === $relcapt):
  13. $name = trim($_POST['userName']);
  14. $pwd = md5(trim($_POST['passWord']));
  15. $where = "`name`='$name'";
  16. $res = $user->select($table,'*',$where);
  17. //判断是否存在用户名
  18. if(count($res)):
  19. $where = "`password`='$pwd'";
  20. $res = $user->select($table,'*',$where);
  21. //判断密码是否正确
  22. if(count($res)):
  23. $nc = $res[0]['nc'];
  24. $img = $res[0]['headimg'];
  25. $_SESSION['userHeadImg'] = $img;//用户头像的文件名写入session
  26. $_SESSION['userNc'] = $nc;//用户昵称写入session
  27. $loginState['status']=1;
  28. $loginState['message']='登录成功';
  29. else:
  30. $loginState['status'] = 0;
  31. $loginState['message']='密码错误';
  32. endif;
  33. else:
  34. $loginState['status'] = 0;
  35. $loginState['message']='用户名不存在';
  36. endif;
  37. else:
  38. $loginState['status'] = 0;
  39. $loginState['message']='验证码错误';
  40. endif;
  41. else:
  42. $loginState['status'] = 0;
  43. $loginState['message']='请求类型错误';
  44. endif;
  45. echo json_encode($loginState);
  46. ?>

1.5 显示效果图

  • 登录成功

  • 验证码错误

2 设置请求头

2.1模拟form表单设置请求头ajaxPostOne.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>ajax中的POST请求</title>
  7. <script>
  8. function addContent() {
  9. var content = document.getElementById('content').value;
  10. //创建一个ajax对象
  11. var ajaxObj = new XMLHttpRequest;
  12. //监听ajax对象
  13. ajaxObj.onreadystatechange = function(){
  14. if((ajaxObj.readyState==4)&&(ajaxObj.status==200))
  15. {
  16. //接收服务传回的json数据并解析
  17. jsObj = JSON.parse(ajaxObj.responseText);
  18. sendPerson = jsObj.person;
  19. sendContent = jsObj.content;
  20. sendDate = jsObj.date;
  21. document.getElementById('sendPerson').innerText=sendPerson;
  22. document.getElementById('showContent').innerText=sendContent;
  23. document.getElementById('sendDate').innerText=sendDate;
  24. }
  25. };
  26. //初始化
  27. ajaxObj.open('POST','ajaxPostOne.php',true);
  28. //设置请求头,模拟表单类型的数组进行发送,application/x-www-form-urlencoded默认
  29. ajaxObj.setRequestHeader('content-type','application/x-www-form-urlencoded');
  30. //发送
  31. //将发送的内容包装成一个对象
  32. var sContent = {
  33. SContent:content
  34. };
  35. //把发送内容序列化为一个json字符串然后发送
  36. ajaxObj.send(JSON.stringify(sContent));
  37. }
  38. </script>
  39. <style>
  40. body{
  41. display: grid;
  42. gap: 5px;
  43. }
  44. p{
  45. background-color: lightseagreen;
  46. border-radius: 10px;
  47. padding: 10px;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <h1>使用ajax-模拟表单-实现无刷新操作</h1>
  53. <textarea name="content" id="content" cols="30" rows="10" placeholder="输入评论内容"></textarea>
  54. <button type="button" onclick="addContent()">添加</button>
  55. <div>
  56. <span>发送人:</span><span id="sendPerson"></span>
  57. <p id="showContent" style="height: 100px;"></p>
  58. <span>发送日期:</span><span id="sendDate"></span>
  59. </div>
  60. </form>
  61. </body>
  62. </html>

2.2处理数据ajaxPostOne.php

  1. <?php
  2. $add['person'] = 'angle';
  3. $add['date'] = date('Y-m-d');
  4. //获取ajax传输过来的数据
  5. $jsonContent = json_decode((key($_POST)),true);//将客户端传来的json数据转换为一个数组
  6. $add['content'] =str_replace('出售','****',$jsonContent['SContent']);
  7. //把add数组序列化为一个json字符串
  8. $jsonPDC = json_encode($add);
  9. //把json字符串返回给ajax对象
  10. echo $jsonPDC;
  11. ?>

2.3模拟json数据设置请求头ajaxPostTwo.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  6. <title>ajax中的POST请求</title>
  7. <script>
  8. function addContent() {
  9. var content = document.getElementById('content').value;
  10. //创建一个ajax对象
  11. var ajaxObj = new XMLHttpRequest;
  12. //监听ajax对象
  13. ajaxObj.onreadystatechange = function(){
  14. if((ajaxObj.readyState==4)&&(ajaxObj.status==200))
  15. {
  16. //接收服务传回的json数据并解析
  17. jsObj = JSON.parse(ajaxObj.responseText);
  18. sendPerson = jsObj.person;
  19. sendContent = jsObj.content;
  20. sendDate = jsObj.date;
  21. document.getElementById('sendPerson').innerText=sendPerson;
  22. document.getElementById('showContent').innerText=sendContent;
  23. document.getElementById('sendDate').innerText=sendDate;
  24. }
  25. };
  26. //初始化
  27. ajaxObj.open('POST','ajaxPostTwo.php',true);
  28. //设置请求头,模拟表单类型的数组进行发送,application/json;charset=utf-8为json格式传输
  29. ajaxObj.setRequestHeader('content-type','application/json;charset=utf-8');
  30. //发送
  31. //将发送的内容包装成一个对象
  32. var sContent = {
  33. SContent:content
  34. };
  35. //把发送内容序列化为一个json字符串然后发送
  36. ajaxObj.send(JSON.stringify(sContent));
  37. }
  38. </script>
  39. <style>
  40. body{
  41. display: grid;
  42. gap: 5px;
  43. }
  44. p{
  45. background-color: lightseagreen;
  46. border-radius: 10px;
  47. padding: 10px;
  48. }
  49. </style>
  50. </head>
  51. <body>
  52. <h1>使用ajax-JSON实现无刷新操作</h1>
  53. <textarea name="content" id="content" cols="30" rows="10" placeholder="输入评论内容"></textarea>
  54. <button type="button" onclick="addContent()">添加</button>
  55. <div>
  56. <span>发送人:</span><span id="sendPerson"></span>
  57. <p id="showContent" style="height: 100px;"></p>
  58. <span>发送日期:</span><span id="sendDate"></span>
  59. </div>
  60. </form>
  61. </body>
  62. </html>

2.4处理数据ajaxPostTwo.php

  1. <?php
  2. $add['person'] = 'angle';
  3. $add['date'] = date('Y-m-d');
  4. //获取ajax传输过来的数据
  5. $data = file_get_contents('php://input');
  6. $jsonContent = json_decode($data,true);//将客户端传来的json数据转换为一个数组
  7. $add['content'] =str_replace('出售','****',$jsonContent['SContent']);
  8. //把add数组序列化为一个json字符串
  9. $jsonPDC = json_encode($add);
  10. //把json字符串返回给ajax对象
  11. echo $jsonPDC;
  12. ?>

代码显示效果

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议