前端代码
利用ajax中的xhr属性,实现在弹窗中即时输出服务端响应结果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta http-equiv="Expires" content="-1">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Pragma" content="no-cache">
<title>Sample</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
html,
body {
line-height: 1.2;
font-size: 14px;
color: rgba(0, 0, 0, .85);
}
html,
body,
button {
font-family: -apple-system, BlinkMacSystemFont, segoe ui, Roboto, helvetica neue, Arial, noto sans, sans-serif, apple color emoji, segoe ui emoji, segoe ui symbol, noto color emoji;
}
button {
display: block;
margin: 20px auto;
width: 120px;
height: 40px;
font-size: 16px;
}
.mask {
z-index: 998;
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, .6);
}
.panel {
z-index: 999;
position: fixed;
top: 50%;
left: 50%;
margin: -280px 0 0 -320px;
padding: 10px;
width: 620px;
height: 540px;
background-color: #fff;
overflow: hidden auto;
box-shadow: 0 0 50px rgba(0, 0, 0, .1);
}
.inner {
width: 100%;
}
</style>
</head>
<body>
<button role="button" type="button">Try</button>
</body>
</html>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
var url = 'https://www.xxx.com/demo/sample/index';
$(function() {
//解除事件绑定
$(document).off('click', '[role="button"]');
//发放激励
$(document).on('click', '[role="button"]', function(e) {
e.stopPropagation();
$('.panel,.mask').remove();
$('body').append('<div class="mask"></div>').append('<div class="panel"><div class="inner"></div></div>');
$.ajax({
async: true,
type: 'POST',
url: url,
headers: {
Accept: 'application/json;charset=utf-8'
},
data: {},
dataType: 'JSON',
beforeSend: function() {},
success: function() {},
error: function() {},
xhr: function() {
if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
var xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 3 || (xhr.readyState === 4 && xhr.status === 200)) {
$('.inner').html(xhr.responseText);
$('.panel').animate({
scrollTop: $('.inner').height()
}, 100);
}
}
return xhr;
}
});
});
});
</script>
后端代码
服务端使用thinkphp6框架,简单模拟返回内容
<?php
namespace app\demo\controller;
use app\demo\controller\Base;
use think\App;
use think\facade\View;
class Sample extends Base
{
protected $app;
/**
* 构造方法
*/
public function __construct(App $app)
{
parent::__construct($app);
}
/**
* index
*/
public function index()
{
if ($this->request->isAjax()) {
set_time_limit(0);
ini_set('memory_limit', '-1');
ob_end_clean();
ob_implicit_flush(1);
for ($i = 0; $i < 10000; $i++) {
echo '<p>' . sprintf('%05d', $i) . '</p>';
usleep(100000);
}
} else {
return View::fetch();
}
}
}