Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

ajax - Django request.is_ajax returning false

I am testing out ajax with Django + jQuery. I have this in my views:

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

and this in my template:

<!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>

My question is - why does this return "Not ajax" to my html page?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know what happened to you. I tested and got a good message: This is ajax. My code:

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...