使用javascript完成一个ajax请求

主入口

导入必要的库

准备工作

@app.route('/content/')
def content():
    return render_template('content.html')

@app.route('/xhr/')
def xhr():
    return render_template('xhr.html')

content.html中的内容为纯文本 ‘test ajax’

xhr.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
</head>
<body>
    <h1>xhr请求</h1>
    <div id="msg"></div>
    <button onclick="">显示内容</button>
    ##点击显示内容的按键后将content页面中的内容显示到div中

</body>
</html>
<script>
    function getData() {
        var xhr;  ##声明一个变量

        ##通过winsow对象判断浏览器版本实例化xhr
        if (window.ActiveXObject) {
            xhr=new ActiveXObject('Microsoft.XHLHttp');
        }
        else if (window.XMLHttpRequest){
            xhr= new XMLHttpRequest();
        }
        else{
            throw new Error('不支持ajax');
        }

        ##指定xhr状态变化关联事件
        ##onreadystatechange请求状态改变事件句柄
        ##xhr.readyState 0 没有发送;1 已打开;2 已接受headers;3 正在载入;4 搞定
        ##xhr.status 200 正常;3XX 重定向;4XX 客户端问题;5XX 服务器端问题
        ##responseText服务器响应文本  1 html;2 json;3 text 
        ##responseXML服务器响应XML
        ##response服务器整个响应

        xhr.onreadystatechange=function(){
            if (xhr.readyState==4 && xhr.status==200){
                document.getElementById('msg').innerHTML=xhr.responseText;
            }
        }

        xhr.open('GET','/content/'); ##初始化请求方式与地址
        xhr.send(); ##发送请求
    }
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值