Django框架中的Ajax Post?

Igo*_*gor 5 django ajax jquery

我在django框架中对ajax/jquery文章进行了一个简单的测试,但是并不真正理解为什么输出没有进入模板页面.任何人?

我可以在firebug的"响应"选项卡中看到帖子的内容,但是我是否尝试返回模板或简单消息,浏览器本身没有任何反应.相反,非ajax帖子按预期工作(加载新页面,发布消息)

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

最终,我希望能够通过jquery将任意非形式变量传递给django视图.可能?谢谢 :)

这是代码 -

的test.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>
Run Code Online (Sandbox Code Playgroud)

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')
Run Code Online (Sandbox Code Playgroud)

urls.py:

(r'^test_results/$', views.test_ajax),
(r'^test/$', views.test),
Run Code Online (Sandbox Code Playgroud)

几乎是空的test_results.html:

<html>
<head>
</head>
<body>
test results
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

Yuj*_*ita 5

我可以在firebug的"响应"选项卡中看到帖子的内容,但是我是否尝试返回模板或简单消息,浏览器本身没有任何反应.相反,非ajax帖子按预期工作(加载新页面,发布消息)

如果你收到回复,你会收到回复.你只是没有做任何事情.

为什么不警告数据并将其附加到<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);
     }
});
Run Code Online (Sandbox Code Playgroud)