php的无刷新操作实现方法分析

2020-02-28 12:01:12王冬梅

php的无刷新操作实现方法。,具体如下:

方法一:

我们通过http的204状态码,页面不跳转。

1.html代码如下:

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <a href="./add.php" rel="external nofollow" >投票</a>
</body>
</html>

add.php代码如下:

<?php
$num = file_get_contents('./num.txt');
$num = intval($num) + 1;
file_put_contents('./num.txt', $num);

header('HTTP/1.1 204 No Content');

方法二:

利用图片加载的特性,来完成请求。

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <input type="button" value="投票" id="addBtn" />
  <div id="request"></div>
</body>
<script type="">
  var addBtn = document.getElementById("addBtn");
  addBtn.onclick = function() {
    //创建img标签
    var img = document.createElement("img");

    //设置标签src属性
    img.setAttribute("src", "add.php");
    document.createElement("request").appendChild(img);
  };
</script>
</html>

方法三:

利用css,javascript的加载特性,完成请求,原理与img加载一样。

方法四:

利用iframe的特性

2.html代码如下:

<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <form action="ret.php" method="post" target="request">
    用户名:<input type="text" name="uname" value="" />
    密码:<input type="password" name="upwd" value="" />
    <input type="submit" name="submit" value="提交" />
  </form>
  <iframe width="0" height="0" frameborder="0" name="request"></iframe>
  <div id="result"></div>
</body>
</html>

ret.php代码如下:

<?php
$uname = !empty($_POST['uname']) ? $_POST['uname'] : '';
$upwd = !empty($_POST['upwd']) ? $_POST['upwd'] : '';

if($uname == 'admin' && $upwd == '123456') {
  echo "<script>parent.document.getElementById('result').innerHTML='OK';</script>";
} else {
  echo "<script>parent.document.getElementById('result').innerHTML='NO';</script>";
}

我们通过设置form提交的target到iframe,使表单无跳转。

ajax能实现文件上传吗?

分析,文件上传,是需要客户端把文件内容发送到服务器,也就是XHR对象在POST数据时,把文件内容也发送给服务器。
也就是XHR对象能够获取你要上传的文件内容,但是出于安全的考虑,JS是无法获取本地文件内容的。

相关文章 大家在看