方法一:
我們通過http的204狀態碼,頁面不跳轉。
1.html代碼如下:
<!DOCTYPE HTML>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<a href="./add.php">投票</a>
</body>
</html>
<?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>
<?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>";
}
ajax能實現文件上傳嗎?
分析,文件上傳,是需要客戶端把文件內容發送到服務器,也就是XHR對象在POST數據時,把文件內容也發送給服務器。
也就是XHR對象能夠獲取你要上傳的文件內容,但是出於安全的考慮,JS是無法獲取本地文件內容的。
ajax插件是如何實現文件上傳的?
1、iframe 2、flash實現,如swfupload 3、html5 (添加了文件讀取api,使ajax上傳文件成為可能。)
