0%

Django添加新的路由

Django如何添加新的路由

Django添加新的路由

  • 首先urls.py文件添加路由

    1
    2
    3
    4
    5
    6
    7
    urlpatterns = [
    url(r'^admin/', admin.site.urls),
    # alt+enter
    url(r"^login/",views.login),
    url(r"^app/addStu/",views.addStu),
    url(r"^register",views.register)
    ]
  • 在views.py中创建函数register

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    def register(request):
    print("register")
    user = request.POST.get("user")
    print(user)
    psd = request.POST.get("psd")
    print(psd)
    #解决跨域问题
    response = HttpResponse(user)
    response["Access-Control-Allow-Origin"] = "*"
    response["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS"
    response["Access-Control-Max-Age"] = "1000"
    response["Access-Control-Allow-Headers"] = "*"
    return response
  • 由于ajax跨域的问题,也需要在settings.py文件中设置,将选中的模块注释

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10

    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',
    ]
  • 我们的ajax请求在前端中使用的,在使用ajax之前,我们需要将jquery链接到我们的项目中

  • 1
    2
     <script src="js/jquery-2.1.0.js" type="text/javascript" charset="utf-8"></script>
    src:jquery的链接地址
  • 调用ajax请求

  • 1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    $.ajax({
    type:"post",//请求的类型
    url:"http://127.0.0.1:8000/register/",//请求的地址[路由]
    async:true, //声明异步请求
    data:{"user":user,"psd":psd},//将参数传递到后台
    dataType:"text", //声明返回的数据的类型,json
    success:function (data) { //请求成功的时候调用的函数,data:后台返回给我们的数据
    alert(data)
    },
    error:function () { //请求的失败的时候,打印
    alert("请求失败")
    }
    })
写文不易,感谢支持!
Writing is not easy. Thank you for your support.