美文网首页
js ajax异步请求

js ajax异步请求

作者: simplerandom | 来源:发表于2020-06-16 19:14 被阅读0次
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #test-image-preview {
        width: 1000px;
        height: 1000px;
    }
</style>

<body>
    <input type="text" id="test-response-text" />
</body>

</html>
<script>
    function success(text) {
        var textarea = document.getElementById('test-response-text');
        textarea.value = text;
    }

    function fail(code) {
        var textarea = document.getElementById('test-response-text');
        textarea.value = 'Error code: ' + code;
    }
    var request = new XMLHttpRequest(); // 新建XMLHttpRequest对象

    request.onreadystatechange = function () { // 状态发生变化时,函数被回调
        if (request.readyState === 4) { // 成功完成
            // 判断响应结果:
            if (request.status === 200) {
                // 成功,通过responseText拿到响应的文本:
                return success(request.responseText);
            } else {
                // 失败,根据响应码判断失败原因:
                return fail(request.status);
            }
        } else {
            // HTTP请求还在继续...
        }
    }

    // 发送请求:
    request.open('GET', 'http://new.toodo.fun/apis?type=contentWu&skey=3f239f68a035d40e1891d8b5fdf032d3');
    request.send();

    alert('请求已发送,请等待响应...');
</script>

相关文章

网友评论

      本文标题:js ajax异步请求

      本文链接:https://www.haomeiwen.com/subject/nxorxktx.html