在代码中使用django中的ajax问题

时间:2010-06-07 11:34:16

标签: ajax django

我是ajax的新手,并使用Django进行Web开发。 现在我的模板包含:sample.html

<html>
<body>
<script language="javascript" type="text/javascript">
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
                // Opera 8.0+, Firefox, Safari
                ajaxRequest = new XMLHttpRequest();
        } catch (e){
                // Internet Explorer Browsers
                try{
                        ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } catch (e) {
                        try{
                                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                        } catch (e){
                                // Something went wrong
                                alert("Your browser broke!");
                                return false;
                        }
                }
        }



        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
                if(ajaxRequest.readyState == 4){
                        document.myForm.time.value = ajaxRequest.responseText;
                }
        }
        ajaxRequest.open("GET", "/showtime/", true);
        ajaxRequest.send(null);
}

</script>



<form name='myForm'>
Name: <input type='text' onBlur="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

在views.py中我的功能是:

def showtime(request):
       string = "Ajax Application"
       data = {"string" : string}
       pprint (data)
       return render_to_response("sample.html",data)

现在,输出不符合预期。模板不会收到服务器发送的响应 代码有什么问题?

2 个答案:

答案 0 :(得分:4)

如果您尝试使用AJAX返回的字符串填充文本字段,则不应使用render_to_response。只需返回字符串。

def showtime(request):
   s = "Ajax Application"
   print "Returning %s"%s #is this line executed?
   return HttpResponse(s, mimetype="text/plain")

答案 1 :(得分:0)

  1. 当您在浏览器中输入时,尝试/ showtime /按预期工作!
  2. 使用像jquery这样的js框架可以节省你实现ajax的时间和精力,例如。请参阅本教程http://lethain.com/entry/2007/dec/11/two-faced-django-part-5-jquery-ajax/
  3. 还有一些你可以使用的django-built-ins,例如request.is_ajax来验证请求是否真的来自ajax!