weixin_33738555 2018-11-13 17:46 采纳率: 0%
浏览 19

来自Ajax的Django和POST

I've been trying to get a POST to my Django views with the final goal to send a 'selected' input (from a clicked #id) and have Django send a response which I can dynamicly show. Using GET I'm able to recieve a response but the POST is giving me problems (I could go for GET but at this time I just want to understand why I'm messing up POST...;))

I have used several guides by now but most are about forms and, to be honest, I have trouble following the documentation (I have little to no background in programming).

Could someone point me in the right direction?

My HTML ('numberinput' is a placeholder for now):

<script>
    $("#test").on(click(function () {
        numberinput = 8;

        $.ajax({
            type: 'POST',
            url: '{% url "rungenerator" %}',
            data: {'numberinput': numberinput},
            dataType: 'json',
            success: function (inputtype) {
                alert(inputtype)

            }

        })
    }))

</script>

<div>
    <form method="POST">
        {% csrf_token %}
        <button type="submit" id="test">Buzzzz Ping</button>

    </form>
</div>

Views:

def rungenerator(request):
    inputtype = "Please make a selection"

    if request.method == 'POST':
        inputtype = request.POST['numberinput',None]
    return JsonResponse(inputtype)

URLS:

url(r'^ajax/rungenerator/$', views.rungenerator, name='rungenerator'),
  • 写回答

1条回答 默认 最新

  • weixin_33737774 2018-11-13 20:12
    关注

    @csrf_exempt Will allow you to bypass the token validation. Please check if your Ajax call is making the cross-origin error. if that the case you should either use cors-headers on your django app. btw using require_http_methods will force the function to check the HTTP method so you can be 100% sure all data that you will get will be POST

    from django.views.decorators.csrf import csrf_exempt
    from django.views.decorators.http import require_http_methods
    from django.http import HttpResponse
    
    @csrf_exempt
    @require_http_methods(["POST"])
    def rungenerator(request):
        inputtype = request.POST.get('numberinput', None)
        payload = {"response":str(inputtype)} if inputtype is not None else {"response":"please type something"}
        return HttpResponse(json.dumps(payload, indent=2),
                                content_type='application/json',
                                status=200) 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器