【问题标题】:use of ajax in django problem with the code在django中使用ajax的代码问题
【发布时间】:2011-02-28 15:56:23
【问题描述】:

我是 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)

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

【问题讨论】:

  • 我在您的模板中没有看到 {{ string }}。你的代码应该做什么?
  • 模板接收什么?时间字段是否填充了完整的 html 页面?
  • 您确定您的网址格式输入正确吗?

标签: ajax django


【解决方案1】:

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

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

【讨论】:

  • 你总是应该返回一个 HttpResponse 对象,比如 return HttpResponse("Ajax Application", mimetype="text/plain")
  • 再次:不要使用 print 语句。在某些服务器设置中,打印语句会导致 HTTP 500 错误(据我记得在 wsgi 或 fcgi 中就是这种情况)。只需返回 HttpResponse。
  • @mawimawi 我不建议他在生产代码中使用它;只是试图确保该函数确实被调用。 OP 还没有显示他的urls.py
【解决方案2】:
  1. 在您在浏览器中键入时尝试 /showtime/ 是否按预期工作!
  2. 使用像 jquery 这样的 js 框架将节省您实施 ajax 的时间和精力,例如。看这个教程http://lethain.com/entry/2007/dec/11/two-faced-django-part-5-jquery-ajax/
  3. 您还可以使用一些 django 内置插件,例如 request.is_ajax 来验证请求是否真的来自 ajax!

【讨论】:

  • is_ajax 很好,但是您无法在浏览器中点击 URL 来检查响应。当我希望同一个视图以不同方式响应 ajax 请求时,我只使用 is_ajax。
猜你喜欢
  • 2020-07-30
  • 1970-01-01
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-31
相关资源
最近更新 更多