0

我试图从对话窗口提交表单并在同一个对话窗口中显示响应。现在我正在尝试使用 Django 视图,该视图将表单(带有验证错误)作为 html 字符串返回。

template = "register.html"
html = render_to_string(template, {'form': form})
return HttpResponse(html, content_type="text/html; charset=utf-8") 

但是我的对话框模式中的功能存在一些问题。我错过了用 HttpResponse 中的新 html 替换“模态/对话框”中的内容的部分。

$('#registerform').submit(function(e){
e.preventDefault();
$.post('register', function(data){ 

//somthing is missing here..             
});
return false;    
});

现在不确定格式,但你明白了。如果任何专家可以指导我正确的方向,我会是一个快乐的人!谢谢

4

1 回答 1

0

这是一个带有 Django 大括号的实现: https ://github.com/brack3t/django-braces

//Inside your click, event whatever call...
...
// Get the token initialy, this is the way to do it 
// using the jQuery cookie plugin 
var $csrftoken = $.cookie('csrftoken');
$.ajax({
    type: 'POST',
    url: '/your/post/url/',
    crossDomain: false,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("X-CSRFToken", $csrftoken);
    },
    success: function(ctx) {
        """
        ctx contains the data your view returns, 
        If you are using Django braces, you could implement the 
        AjaxResponseMixin mixin which allows you to return a dict 
        to the view.
        """
    },
});
...

视图.py

class AjaxDosomethingView(JSONResponseMixin, AjaxResponseMixin, View):

    def post_ajax(self, request, *args, **kwargs):
        """
        Do some stuff and create the response object
        """
        myid = request.POST.get('somevar')
        result = MyModel.objects.get(id=myid)
        response = {'id': result.id, 'title': result.title}

        return self.render_json_response(response, 200)
于 2014-01-21T21:27:04.237 回答