使用AJAX与PHP实现每隔10秒检查变量直至为yes
实现循环AJAX检查状态直到返回"yes"
没问题,我来帮你搞定这个循环检查的需求。核心思路是写一个递归函数,每次请求shared.php后根据返回结果决定是继续定时检查还是停止并展示成功信息。下面分原生JS和jQuery两种方案给你参考:
原生JavaScript方案
首先在页面里加一个用来显示状态的元素:
<div id="status-message"></div>
然后是核心的JS代码:
function checkSharedStatus() { // 创建AJAX请求实例 const xhr = new XMLHttpRequest(); xhr.open('GET', 'shared.php', true); xhr.onload = function() { if (xhr.status >= 200 && xhr.status < 300) { // 去除返回值里的多余空格和换行,避免判断出错 const response = xhr.responseText.trim(); const statusElement = document.getElementById('status-message'); if (response === 'yes') { // 状态达标,显示成功信息并停止循环 statusElement.textContent = '分享完成!现在可以进行下一步操作啦~'; statusElement.style.color = 'green'; } else if (response === 'no') { // 状态未达标,提示后10秒再次检查 statusElement.textContent = '还在等待分享... 10秒后自动重试'; statusElement.style.color = 'orange'; setTimeout(checkSharedStatus, 10000); // 10秒后递归调用自身 } else { // 处理意外返回值,比如服务器输出了其他内容 statusElement.textContent = '请求返回异常,10秒后重试'; statusElement.style.color = 'red'; setTimeout(checkSharedStatus, 10000); } } else { // 请求状态码异常,比如404/500 const statusElement = document.getElementById('status-message'); statusElement.textContent = `请求失败(状态码:${xhr.status}),10秒后重试`; statusElement.style.color = 'red'; setTimeout(checkSharedStatus, 10000); } }; xhr.onerror = function() { // 网络连接错误,比如断网了 const statusElement = document.getElementById('status-message'); statusElement.textContent = '网络连接异常,10秒后重试'; statusElement.style.color = 'red'; setTimeout(checkSharedStatus, 10000); }; // 发送请求 xhr.send(); } // 页面加载完成后自动启动第一次检查 window.addEventListener('load', checkSharedStatus);
jQuery简化方案(如果你已经引入jQuery)
同样先加状态显示元素:
<div id="status-message"></div>
然后是jQuery版本的代码:
function checkSharedStatus() { $.get('shared.php') .done(function(response) { const trimmedResponse = $.trim(response); const $status = $('#status-message'); if (trimmedResponse === 'yes') { $status.text('分享完成!现在可以进行下一步操作啦~').css('color', 'green'); } else if (trimmedResponse === 'no') { $status.text('还在等待分享... 10秒后自动重试').css('color', 'orange'); setTimeout(checkSharedStatus, 10000); } else { $status.text('请求返回异常,10秒后重试').css('color', 'red'); setTimeout(checkSharedStatus, 10000); } }) .fail(function() { const $status = $('#status-message'); $status.text('请求失败,10秒后重试').css('color', 'red'); setTimeout(checkSharedStatus, 10000); }); } // 页面就绪后启动检查 $(document).ready(function() { checkSharedStatus(); });
关键注意事项
- 确保
shared.php的输出只有yes或no,不要有任何多余的内容(比如空格、换行、调试信息)。建议在PHP里最后只写echo $shared;,并且前面不要有其他echo/print语句,否则会导致判断失效。 - 如果需要传递参数(比如用户ID),可以在请求URL里拼接,比如原生JS里用
xhr.open('GET', 'shared.php?user_id=123', true);,jQuery里用$.get('shared.php', {user_id: 123})。 - 你可以根据自己的UI需求修改提示信息的样式,比如添加图标、动画,让用户体验更好。
内容的提问来源于stack exchange,提问作者OneZeroOne
相关产品推荐
相关产品推荐

