AJang中的Django GET请求

isa*_*sar 3 django ajax

我需要使用AJAX获取一些HTML.只要我使用jQuery,我的视图就可以正常工作:

view.py

def my_ajax(request):
    if request.is_ajax():
        my_form = MyForm()
        context = {
            'form': my_form
        }
        return render(request, 'myapp/form.html', context)
Run Code Online (Sandbox Code Playgroud)

main.js(jQuery加载)

$(document).ready(function() {
    $('#foo').click(function() {
        $('#bar').load('{% url "myapp:form" %}');
    });
});
Run Code Online (Sandbox Code Playgroud)

如果我使用JavaScript XMLHttpRequest我必须if request.is_ajax():从视图中删除否则我得到错误The view myapp.views.my_ajax didn't return an HttpResponse object. It returned None instead.

main.js(XMLHttpRequest)

(function() {
    document.getElementById('foo').addEventListener("click", function() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            document.getElementById("bar").innerHTML = xhttp.responseText;
        }
    };
    xhttp.open("GET", '{% url "myapp:form" %}', true);
    xhttp.send();
    }, false);
})();
Run Code Online (Sandbox Code Playgroud)

我在XMLHttpRequest中做错了什么?我肯定错过了一些东西,但这次我想使用Vanilla JavaScript.谢谢!

Ser*_*aev 5

尝试添加xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');之后var xhttp = new XMLHttpRequest();.