python - 无法在 Django 中使用 AJAX POST

标签 python ajax django python-3.x

我无法在 Django 中执行 POST ajax 请求。如果我执行 GET 请求,效果很好。我认为这可能是 csrf token 问题,但我可以让它工作

我的看法:

@login_required
def add_share_points(request):
    user = request.user
    profile = request.user.profile

    if request.method == 'POST':
        value = 5.0

        # Premia o usuário ao compartilhar conteúdo
        VirtualCurrencyTransaction.objects.create(
            user=request.user,
            reason=2,
            description='Você completou seu perfil',
            value=value
        )

    return "ok"

我的 AJAX 请求:

$('.my-button').on('click', function(e) {
    e.preventDefault();
    var pointsCount = $(this).hasClass('homepage-facebook-share') ? 3 : 2;
    $.ajax({
        type:"POST",
        url: "/add_share_points",
        data: {
            points: pointsCount,
        }
    }).done(function() {
        alert('Posting completed.');
    }).fail(function(){
        alert('Error while posting.');
    });
});

在我的脚本中,我也有这样的设置:

function csrfSafeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/).test(method);
}

$.ajaxSetup({
    crossDomain: false,
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader('X-CSRFToken', CSRF_TOKEN);
        }
    }
});

我的代码有什么问题吗?它给了我一个 500 错误代码,但日志中没有进一步的解释。

最佳答案

我会指出一些需要纠正的地方,有些只是以 django 方式实现的方法,而不是问题。

在你看来

 return HttpResponse(
            json.dumps({'result': 'ok',}),
            content_type="application/json"
        )

在你的ajax中

url: "/add_share_points",

应该是:

url : {% url '<name in url.py>' %},

并且您需要添加(到数据对象):

 csrfmiddlewaretoken: '{{ csrf_token }}'

在ajax请求中,在数据后面插入以下内容:

// handle a successful response
success : function(json) {
     if (json.result=== 'ok'){
         console.log('It works!');
     }else{
         console.log('Something wrong with response');
     }
// handle a non-successful response
error : function(xhr,errmsg,err) {
    console.log(err);
}

在您的脚本中

使用'{{ csrf_token }}'代替CSRF_TOKEN

Please use my suggestions and give me feedback and I will update the answer. The two with csfrtoken are probably the problems your having. If you put Django in Debug mode it will be easyer to find out.

我的建议

创建 form以及您需要发布的内容才能在验证过程中获得某些功能。

关于python - 无法在 Django 中使用 AJAX POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38820720/

相关文章:

javascript - 使用 AJAX 将数组发布到 MVC C#

python - Django:生成报告

python - 使用下面代码中的 "i-=smallest"语句,我打算更改原始数组 arr,但这并没有发生。我该怎么办?

python - 如何拥有一个包含四个表的 Django 关系数据库?

javascript - Ajax jquery mysqli 更新

javascript - 页面转换期间的 Ajax 调用

java - 我的 RabbitMQ 订阅代码不起作用

python - Matplotlib,避免 plot_trisurf() 中不需要的三角形

django - 具有多对多和直通表的 Graphene-django

python - Django UserProfile ...没有密码