Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 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 Reply

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...