梅川酷芷 2018-07-27 12:43 采纳率: 50%
浏览 954
已采纳

哪位大哥能帮我写个原生的 JS getJSON

哪位大哥能帮我写个原生的 JS getJSON,在此感谢了。
不是异步请求,
请求地址:get2.php?uuid=sssssss
失败返回的JSON

{"error_code": 0, "reason": "success", "resultcode": 200, "qr_code": null}
点击按钮后执行一秒轮询一次get2.php?uuid=sssssss
每轮询一次,按钮上的标题显示次数。
轮询35秒后qr_code还是null,就让用户点击刷新页面。
直到qr_code 栏里是URL 地址。然后执行第二次 请求,请求地址:get5555.php?url=把刚取出qr_code的值。然后得到get5555.php返回的值,弹窗显示

现有实现一次请求的源码。我需要实现两次不同请求地址

 <input type="button" id="but" value="开始" onclick="run(1);" />
<script type="text/javascript">
function run(n) {
    var xhr = new XMLHttpRequest();
    xhr.open('get','get2.php?uuid=sssssss&time='+new Date().getTime());
    xhr.onreadystatechange = function () {
        if (xhr.readyState==4 &&xhr.status==200) {
            document.getElementById("but").value = n;
            var data = JSON.parse(xhr.responseText);
            if (data.qr_code!=null) {
                location.href = data.qr_code;
            } else if (n<35) {
                setTimeout(function(){
                    run(n+1);
                }, 1000);
            } else {
                alert("刷新页面");
                location.reload();
            }
        }
    }
    xhr.send();
}
</script>
  • 写回答

1条回答 默认 最新

  • 天际的海浪 2018-07-27 13:37
    关注
    <input type="button" id="but" value="开始" onclick="run(1);" />
    <script type="text/javascript">
    
    function getAjax(url,callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('get',url+(url.indexOf("?")==-1?"?":"&")+'time='+new Date().getTime());
        xhr.onreadystatechange = function () {
            if (xhr.readyState==4 &&xhr.status==200) {
                callback(xhr.responseText);
            }
        }
        xhr.send();
    }
    
    function run(n) {
        getAjax("get2.php?uuid=sssssss",function (data) {
            document.getElementById("but").value = n;
            data = JSON.parse(data);
            if (data.qr_code!=null) {
                getAjax("get5555.php?url="+encodeURIComponent(data.qr_code),function (data) {
                    alert(data);
                });
            } else if (n<35) {
                setTimeout(function(){
                    run(n+1);
                }, 1000);
            } else {
                alert("刷新页面");
                location.reload();
            }
        });
    }
    </script>
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型