jquery - Django 框架中的 Ajax Post?

标签 jquery ajax django

我在 django 框架内对 ajax/jquery 帖子进行了简单的测试,但并不真正理解为什么输出没有进入模板页面。有人吗?

我可以在 firebug 的“响应”选项卡中看到帖子的内容,但无论我尝试返回模板还是简单的消息,浏览器本身都不会发生任何情况。相反,非 ajax 帖子按预期工作(加载新页面,发布消息)

我是 ajax/jquery/django 的新手,所以请原谅我的无知:)

最终,我想要做的是通过 jquery 将任意非表单变量传递到 django View 。可能的?谢谢:)

这是代码--

测试.html:

<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
   $(document).ready(function() {
       $("#testForm").submit(function(event){
           event.preventDefault();
           $.ajax({
                type:"POST",
                url:"/test_results/"
                    });
       });
       return false;
    });
</script>
</head>
<body>
        <form id="testForm" action="/test_results/" method="post">
            <input type="submit" id="go" name="go" value="Go!">
        </form>
</body>
</html>

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse


    def test_ajax(request):
        if request.is_ajax():
            message = "Yes, AJAX!"
        else:
            message = "Not Ajax"
        return HttpResponse(message)
        #alternative test: return render_to_response('test_results.html')

url.py:

(r'^test_results/$', views.test_ajax),
(r'^test/$', views.test),

和几乎空的 test_results.html:

<html>
<head>
</head>
<body>
test results
</body>
</html>

最佳答案

I can see the contents of the post in firebug's 'response' tab, but whether I try to return a template or a simple message, nothing happens in the browser itself. Conversely, a non-ajax post works as expected (loads new page, posts message)

如果您收到回复,您就会收到回复。你只是没有用它做任何事情。

为什么不提醒数据并将其附加到 <body>例如:

$.ajax({
     type:"POST",
     url:"/test_results/",
     data: {
            'arbitrary-data': 'this is arbitrary data',
            'some-form-field': $("myform input:first").val(), // from form
            'background-color': $("body").css("background-color")
            // all of this data is submitted via POST to your view.
            // in django, request.POST['background-color'] 
     },
     success: function(data){
         alert(data);
         $("body").append(data);
     }
});

关于jquery - Django 框架中的 Ajax Post?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5304517/

相关文章:

javascript - 找到输入框中字符串被删除的部分

javascript - AJAX jQuery 头像上传

php - ajax后复制页面内容到同一页面

python - Django 更新而不是插入新记录

django - 重定向 Django View

python - 1 个 django 应用程序中约有 20 个模型

javascript - 为什么不在选项卡中拉伸(stretch)我的 canvasjs 图表

javascript - 如何在每个页面上动态突出显示菜单项?

javascript - 如何从ajax获取发送响应到脚本

jquery - Bootstrap 弹出窗口 : reload content with ajax