背景:

python小白准备用python写个后台项目,前后台交互的时间遇到一些问题,记录如下:

代码结构:

目录结构:

前台请求:
<script src="/static/js/jssha256.js" type="text/javascript"></script> <script
src="/static/js/jquery.min.js" type="text/javascript"></script> <script>
function regist() { var username = document.getElementById("username").value;
var password = SHA256_hash(document.getElementById("password").value); $.ajax({
url: '/regist_url/', type: "POST", data: JSON.stringify({ username : username,
password : password }), dataType:"json", success: function (data) {
console.log("后台返回数据 ",data) } }); } </script>
urls.py中配置:
urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/',
views.login), url(r'^regist_url/', views.regist_url), ]
在views.py中定义regist_url方法:
def regist_url(request): data = json.loads(request.body) username =
data["username"] password = data["password"] print "用户名:"+username print
"密码:"+password return HttpResponse(request.body)
启动项目,执行/regist_url/请求。

后台打印:

同时return HttpResponse(request.body)返回到前台,前台打印:

这样,前后台交互就好了!

注意:

1.Django对Post请求有中间件防御机制csrf,会出现403 Forbidden错误

有两种解决方法:

(1):直接在settings.py中将django.middleware.csrf.CsrfViewMiddleware全局注释,
MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware', ]
(2).或者对views.py的方法上新增@csrf_exempt注解,去除csrf防御
from django.views.decorators.csrf import csrf_exempt @csrf_exempt def
regist_url(request): data = json.loads(request.body) username =
data["username"] password = data["password"] print "用户名:"+username print
"密码:"+password return HttpResponse(request.body)
2.请求报错

RuntimeError: You called this URL via POST, but the URL doesn't end in a slash
and you have APPEND_SLASH set. Django can't redirect to the slash URL while
maintaining POST data. Change your form to point to 127.0.0.1:8000/regist_url/
(note the trailing slash), or set APPEND_SLASH=False in your Django settings.

将改为,加上“/”

技术
©2019-2020 Toolsou All rights reserved,
JVM概述VUE+Canvas 实现桌面弹球消砖块小游戏javascript事件(零基础详解)Pikachu漏洞练习平台明解c/c++程序的内存模型--内存四区python实现vlookup_干货一:怎么在python里面实现vlookupswift 5.0 创建一个获取验证码的按钮,实现倒计时效果首期500亿,成立新部门,腾讯准备做什么?关于蓝桥杯大赛,你应该了解的那些事!解决Selenium ActionChains拖动元素无效