weixin_33701251 2012-02-25 02:12 采纳率: 0%
浏览 66

如何将ajax与django结合使用?

我希望获得有关将ajax与django结合使用的一些建议。

假设我有一个功能:

def add_comment(request, pk):
  if request.method == 'POST' and request.is_ajax():
    comment_form = CommentForm(request.POST)
    if comment_form.is_valid():
      comment = comment_form.save(commit=True)
      comment.save()
    json = simplejson.dumps(comment, ensure_ascii=False)
   return HttpResponse(json, mimetype='application/json')
  return render_to_response({{ post.id }}', {'comment': comment,}), context_instance=RequestContext(request), mimetype='application/json')

并且我正尝试使用ajax函数将评论发布到页面,而无需重定向:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script></javascript>
<script type="text/javascript">
  $(document).click(function()
  {
   $('#comment_form').submit(function()
   {
    var dataString = $('#comment_form').serialize();
    $.ajax({
      type: 'POST',
      url: '',
      data: dataString,
      success: function(data){
        $('').html(data);
      },
    });
    return false;
    });
  });

</script>

我想让页面加载没有重定向的评论,请帮帮我吧!

  • 写回答

2条回答 默认 最新

  • ℡Wang Yan 2012-02-25 05:10
    关注

    This can helps:

    this could be your view:

    import json
    
    def add_comment(request, pk):
        if request.method == 'POST' and request.is_ajax():
            comment_form = CommentForm(request.POST)
            if comment_form.is_valid():
                comment = comment_form.save(commit=True)
                comment.save()
                json_response = json.dumps({"status":"Success"})
                return HttpResponse(json_response)
            errors = {}
            for k, v in job_type_form.errors.items():
                errors[k.capitalize()] = v
            response = {
                'success': False,
                'errors': errors
            }
            return HttpResponse(json.dumps(response))
    

    and your jquery could be like this:

    $('#comment_form').submit(function() {
        var dataString = $('#comment_form').serialize();
        $.ajax({
            type: 'POST',
            url: '',// you need to put this to something like '{% url to_your_view %}'
            data: dataString,
            dataType: 'json'
            success: function(data){
                // you can access to your json object like data.status or data.something
                $('').html(data.status);
            },
        });
        return false;
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥100 有人会搭建GPT-J-6B框架吗?有偿
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名