在django中使用ajax的问题​​与代码 [英] use of ajax in django problem with the code

查看:72
本文介绍了在django中使用ajax的问题​​与代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to ajax and using Django for web development. Now My Template contains : 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中,我的功能是:

In views.py my function is :

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

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

Now, The output is not as expected . The template does not receives the response sent by the server What is wrong with the code ?

推荐答案

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

If you're trying to populate the text-field with AJAX returned string, you should not use render_to_response. Just return the string.

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

这篇关于在django中使用ajax的问题​​与代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆