javascript - 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 代码处的按钮时,但不是随机数,为什么?谁能帮我?
解决方案
推荐阅读
- javascript - 更改关于 discord.js 中图像的页脚
- cmake - target_link_libraries:PRIVATE|PUBLIC|INTERFACE 的默认设置
- python-3.x - elasticsearch5的身份验证异常
- system.reactive - 如何实现你自己的合并操作符,它可以正确地合并冷的 observables
- docker - docker-compose 等待启动,直到挂载主机文件系统
- python - 规范化python
- javascript - 外层 div 有点击功能,内层 div 没有
- python - 如何以矢量化形式计算这种乘法?
- javascript - Moment.js 从现在/今天在几天、几个月和几年前
- android - 登录错误的 Nativescript 示例应用程序:活动用户已存在。请在登录前注销活动用户