【问题标题】:Ajax response redirectAjax 响应重定向
【发布时间】:2015-03-29 11:38:23
【问题描述】:

我的问题在于我执行 ajax 请求,我的 django 视图处理视图并返回 JsonResponse,其中包含将替换旧内容的内容。不幸的是,响应不会替换旧内容 - 我在内容上得到重定向,页面看起来像:

{"content": "<h3>\u0421\u043e\u043e\u0431\u0449\u0435\u043d\u0438\u0435 \u043e\u0442\u043f\u0440\u0430\u0432\u043b\u0435\u043d\u043e</h3>\n<div>\n    <a href=\"/\">\u0412\u0435\u0440\u043d\u0443\u0442\u044c\u0441\u044f \u043d\u0430 \u0433\u043b\u0430\u0432\u043d\u0443\u044e \u0441\u0442\u0440\u0430\u043d\u0438\u0446\u0443</a>\n</div>", "success": true}

js:

$( '#main' ).on( 'click', '#submit', function() {
    $form = $( '#form' );
    $.ajax({
        type: $form.attr('method'),
        dataType: "JSON",
        url: $form.attr('action'),
        data: {
            form: $form.serialize()
        }
    }).done( function( response ) {
        console.log('ok');
        $( '#old' ).remove();
        $( '#contact' ).append(response.content);
    })
});

查看:

     ...
                content = render_to_string('mock.html')
                return JsonResponse({
                    'success': True,
                    'content': content
                })
...

我该如何解决?

【问题讨论】:

  • 内容还是上下文??
  • 对不起 - 内容

标签: jquery ajax django jsonresponse


【解决方案1】:

我相信你需要这样做:

$('#form').on('submit', function(event){
    event.preventDefault();
    $form = $('#form');
    $.ajax({
        type: $form.attr('method'),
        dataType: "JSON",
        url: $form.attr('action'),
        data: {
            form: $form.serialize()
        }
    }).done( function( response ) {
        console.log('ok');
        $( '#old' ).remove();
        $( '#contact' ).append(response.content);
    })
});

您需要阻止表单提交。

另一种方法是使用jQuery Form Plugin

接下来您应该将 CSRFToken 添加到您的 Ajax 标头中,更多信息请参见 here

【讨论】:

  • 我尝试使用 preventDefault() 方法,但随后我从服务器收到 403 Forbidden 响应 - 为什么我也不知道(
  • 我没有使用 django 的经验,但也许这会有所帮助? docs.djangoproject.com/en/dev/ref/csrf/#ajax 并保留代码中的 prevent default 行或返回 false,您肯定需要它。
  • 没问题,我已经更新答案完整了。
【解决方案2】:

确保您在发送 csrfmiddlewaretoken 时将其与您的 ajax 请求一起发送(如果它是一个帖子)。否则你会得到一个 403 并且可能是一个重定向。

对此进行测试的一种快速方法是将@csrf_exempt 装饰器添加到您的视图中。

【讨论】:

    【解决方案3】:

    你试过了吗:

    $( '#contact' ).html(response.content);
    

    你想替换它吗?

    【讨论】:

    • 是的,但问题不在其中 - .done() 方法不起作用,因为我认为响应重定向到 {"content": "

      \u04... 和.done() 方法没有运行。但是为什么我得到重定向而不是 .done() 运行我不知道

    猜你喜欢
    • 2018-11-23
    • 2016-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多