小编典典

Django request.is_ajax返回false

ajax

我正在用Django + jQuery测试ajax。我认为:

def ajax_test(request):
    if request.is_ajax():
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)

这在我的模板中:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.6.4.js"></script>
</head>
<body>
<script>
$.get("/ajax_test", function(data) {
    alert(data);
    });
});
</script>
</body>
</html>

我的问题是-为什么这会在我的HTML页面中返回“ Not ajax”?


阅读 296

收藏
2020-07-26

共1个答案

小编典典

我不知道你怎么了 我测试并取得了良好的消息:This is ajax。我的代码:

urls.py

url(r'^$', 'myapp.views.home', name='home'),
url(r'^ajax_test/$', 'myapp.views.ajax_test', name='ajax_test'),

views.py

def home(request):
    return render_to_response('home.html', {},
                          context_instance=RequestContext(request))

def ajax_test(request):
    if request.is_ajax():
        message = "This is ajax"
    else:
        message = "Not ajax"
    return HttpResponse(message)

templates / home.html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $(document).ready(function () {
        $.get("/ajax_test/", function (data) {
            alert(data);
        });
    });
</script>
</body>
</html>
2020-07-26