开发者

Can't do an AJAX call with Python and Django

I am still learning to do javascript and django and yesterday I tried to do a simple hello world ajax exercise.

Server logs show that python code is being called but somehow django/python does not return anything when I check the xmlhttp.responseText and responseXML in firebug.

UPDATE: I removed the checking of the http status returned so that code immediately goes to print the output from the server

<html>
<head>
 <title>Javascript example 1</title>
 <script type="text/javascript">
  function doAjax() 
  {
   xmlhttp = new XMLHttpRequest();
   xmlhttp.onreadystatechange = function() {
       alert("response text: "+xmlhttp.responseText+"\n"
             +"response XML: "+ xmlhttp.responseXML);
       if (xmlhttp.responseText!="") {
            $("thediv").innerHTML=xmlhttp.responseText;
       }      
   }   
   xmlhttp.open("GET","http://127.0.0.1/test/",true);
   xmlhttp.send(); 
  }
  function $(element){
    return document.getElementById(element);
  }
 </script>
</head>
<body>

 <input type="button" value="click me" onClick=javascript:doAjax()>
 <br/><br/>

 <div id="thediv">
  some test
 </div>

</body>
</html>

my views.py

from django.http import HttpResponse

def test(request):
 response_string="hello"
 return HttpResponse(response_string,mimetype='text/plain')

my urls.py

from django.conf.urls.defaults import *
from project1.views im开发者_StackOverflowport test

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
        (r'^test/$', test)
    # Example:
    # (r'^project1/', include('project1.foo.urls')),

    # Uncomment the admin/doc line below and add 'django.contrib.admindocs' 
    # to INSTALLED_APPS to enable admin documentation:
    # (r'^admin/doc/', include('django.contrib.admindocs.urls')),

    # Uncomment the next line to enable the admin:
    # (r'^admin/', include(admin.site.urls)),
)

UPDATE

Here is the code in action

Can't do an AJAX call with Python and Django


I just tested your code. When I clicked the "click me" button, a request was indeed made to the test view. I was able to confirm this. However, unlike what you said the view is returning the HttpResponse. To verify this yourself, access the http://localhost:8000/test/ url using your web browser. See what happens.

At first blush your problem seems to be JavaScript related. I don't know what exactly is going wrong but I'll try to debug the JS code and see.

Update

I was able to confirm that the error is indeed with the JavaScript that you are using. I found two errors. First:

if (xmlhttp.readyState==4 && xmlhttp.status==0)

Shouldn't the status be 200? So I changed it to:

if (xmlhttp.readyState==4 && xmlhttp.status==200)

Update 2

Found that I missed the $ function.

The problem is that there are two if conditions. When first evaluates to true, the contents of the div are indeed updated to "hello". However the second if (xmlhttp.responseXML!="") also evaluates to true (null is != "", hence) and wipes out the contents of the div.


Its good to use core JavaScript when learning but you should definitely use some framework such as jQuery or Prototype as you progress. Frameworks allow to keep your code concise, develop faster and also insulate you from the cross-browser compatibility issues.

Using jQuery your code would have been something like this:

<html>
<head>
 <title>Javascript example 1</title>
 <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
 <script type="text/javascript">
  function doAjax() 
  {
    $.ajax({
      url: 'http://localhost:8000/test/',
      success: function(data) {
        $('#thediv').html(data); //jQuery equivalent of  document.getElementById('thediv').innerHTML = data
      }
    });
  }
 </script>
</head>
<body>

 <input type="button" value="click me" onClick="javascript:doAjax()"/>
 <br/><br/>

 <div id="thediv">
  some test
 </div>

</body>
</html>

Since jQuery provides with a default $() function, you do not need to define them in your code in case you use the framework.

Though this answer is slightly off-track, I hope it will be useful to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜