weixin_33713350 2012-11-07 05:28 采纳率: 0%
浏览 27

Django中的Ajax问题

I'm using ajax in django first times .. I read some tutorials on the net and I'm trying to make a simple form which posts some information via ajax.

Here is my html form

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script type="text/javascript">
function send_request()
{

 $.ajax({
                            type:"POST",
                            url:"/ajaxredirect/",


       });

}
</script>
<button type="button" onclick="send_request();">change content</button>

and it is my view

def Ajaxquery(request):
        if request.is_ajax():
                return HttpResponse("ok")
        else:
                return HttpResponse("error")

it does nothing when i am click on change content button in browser.

Any suggestions would be apperciated

  • 写回答

1条回答 默认 最新

  • weixin_33699914 2012-11-07 06:39
    关注

    Here is basic request/response setup I have made use of. I got the JSONResponse and AjaxResponse mixins from the Django Braces Module. I also made sure to include the following Django CSRF fix to prevent my AJAX request from being treated as a cross site request forgery.

    JQuery:

    <script type="text/javascript">
    function send_request() {
        $.ajax({
            type: 'POST',
            url: '/ajaxredirect/',
            data: $('#your_form').serialize(),
            crossDomain: false,
            success: function(ctx) { console.log(ctx); },
        });
    }
    </script>
    

    Views.py

    from django.views.generic import View
    from braces.views import JSONResponseMixin, AjaxResponseMixin
    
    class AjaxResponseView(JSONResponseMixin, AjaxResponseMixin, View):
        def post_ajax(self, request, *args, **kwargs):
            data = request.POST.items() # form data
            ctx = {'hi': 'hello'}
            return self.render_json_response(ctx)
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?