首页 > 解决方案 > ajax + django,点击按钮随机

问题描述

我在使用 django 和 ajax 时遇到了一点问题。有一个代码views.py

def rand(request):
data = {}
action = request.POST.get('action')
if action == 'NeedRandom':
    data['result'] = random.randint(0,1000000)
else:
    data['result'] = 'Error'
return render(request, 'registers/myaction.html', data)

网址.py

urlpatterns = [
    path('myaction/', views.rand, name='my-action'),
]

和一些脚本

$(document).ready(function(){
    // Forming csrf_token
    function getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie != '') {
            let cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                let cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    };

    let data = {}

    $('.mybutton').on('click', function(e){
        data['action'] = 'NeedRandom';
        data['csrfmiddlewaretoken'] = getCookie('csrftoken');
        SendAjax();
    });

    function SendAjax(){
        $.ajax({
            url: 'http://localhost:8000/myaction',
            method: 'POST',
            data: data,
            cached: true,
            success: function(data){
                console.log(data);
            },
            error: function(e){
                console.log(e);
            }
        })
    }
})

并在文件 myaction.html 处进行按钮

{% extends 'base.html' %}
{% block content%}
   <input type="submit" class="mybutton" value="random number">
{% endblock %}

当我单击模板页面 html 代码处的按钮时,但不是随机数,为什么?谁能帮我?

标签: javascriptdjangoajax

解决方案


推荐阅读