xhr的基本使用

xhr兼容性问题

xhr对象的获取方式在IE和非IE下是需要使用不同方法。
语法:
标准浏览器支持的方法为:XMLHttpRequest()
IE浏览器支持的方法为:ActiveXObject()
例子:
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else if(window.ActiveXObject){
xhr = new ActiveXObject();
}

使用

document.querySelector(".sentence").addEventListener("click", function(){
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "{% url 'hans' %}?word={{ one.word }}", true);
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && xhr.status == 200){
            let info = xhr.responseText;
            let o = eval("("+info+")");     // 或者 let o = JSON.parse(info)
            document.querySelector("#sentence").innerHTML = o.sentence;
        }
    }
    xhr.send();
})

xhr提交post请求

    <script>
        let xhr = new XMLHttpRequest();
        let formData = new FormData();
        formData.append("name", "catfish");
        xhr.open("post", "{% url 'index' %}", true);
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4 && xhr.status == 200){
                let info = xhr.responseText;
                let o  = JSON.parse(info);
                document.querySelector("p").innerHTML = o.name;
            }
        }
        xhr.send(formData);
    </script>

django xhr提交post请求方法

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def post_data(request):
      pass
posted @ 2020-10-08 15:17  小默同学  阅读(669)  评论(0编辑  收藏  举报