django框架下ajax獲取cookie和session的方法以及簡單的vue


Django的配置:

  pycharm中創建django工程之后注釋掉MIDDLEWARE項中的'django.middleware.csrf.CsrfViewMiddleware'。此處作用是為了能夠讓js獲取到cookie值

  同時為了使用mysql,我們在setting中修改DATABASES中的'default'項為

        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_test_shop1',
        'HOST':'127.0.0.1',
        'PORT':3306,
        'USER':'root',
        'PASSWORD':'1415926',    

  參數一目了然無需多講

  在django的控制台下執行python manage.py startapp 你的app項目名來新建一個app項目,此后的工程都在這里寫。然后在setting中的INSTALLED_APPS項中注冊app,添加'django.apps.你的app的名字Config'

  同時在setting中添加以下代碼來尋找static路徑和模板代碼路徑

STATICFILES_DIRS=[
    os.path.join(BASE_DIR,'static')
]

  開啟調試功能的代碼為在setting中添加

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

  為了使用現成的數據庫中的數據,我們可以通過在控制台中執行python manage.py inspectdb來獲取代碼,復制粘貼到app中的model文件中

  html模板中若為了使用django的模板語言需要在開頭加上{% load static %}

Django中后端的編寫

  以上准備工作完成之后在app項目文件夾里的urls里如下配置

from django.contrib import admin
from django.urls import path
from tableapp.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',indexRender_CookieAndSession),
    path('test',testAjax_CookieAndSession),
    path('goTestRender',goTestRender),
    path('getSession',getSession),
]

  path的第一個參數為前端的請求地址,第二個參數為調用的函數

  然后就在view文件里編寫函數即可

from django.shortcuts import render
from tableapp.models import *
from django.views.static import HttpResponse
from django.http import JsonResponse
from tableapp.models import *
import json
from django.views.decorators.csrf import csrf_exempt
# Create your views here.

def getSession(request):
    return JsonResponse({"result":request.session.get(json.loads(request.body).get("key"))})

def indexRender_CookieAndSession(request):
    #測試session
    request.session["t1_session"]="session1"
    #刪除session: del request.session["t1_session"]
    #網頁轉發到index.html
    rsp = render(request,"index.html")
    #測試cookie設置
    rsp.set_cookie("t1_cookie",233)
    #刪除cookie: rsp.delete_cookie("t1_cookie")
    return rsp

def goTestRender(request):
    return render(request,"test.html")

# @csrf_exempt
def testAjax_CookieAndSession(request):
    #request是json格式傳過來的參數,需要轉換成字典對象
    params = json.loads(request.body)
    print("testParamInteger:",params["testParamInteger"])
    print("testParamString:", params["testParamString"])
    # 測試session
    request.session["t2_session"] = "session2"

    #orm簡單的兩表查詢
    #   用模型類.objects來進行數據庫操作,filter等同於where操作,values_list將查詢結果轉換成結果元祖,而非values的字典對組成的json對象形式。可以通過切片進行選取操作,[開始位置:結束位置:隔幾個取一個](以上參數和切片一樣可以任意省略)
    data = TGoods.objects.filter(goods_status=1).values_list("goods_id","goods_name","goods_price","type__t_g_type__type_name")[0:10:1]
    title = ("商品ID","商品名","商品價格","商品類別","操作")
    result = {"result":1,"data":data,"title":title}
    #這里可以替換成 return JsonResponse(result)
    resp = HttpResponse(json.dumps(result),content_type="application/json")
    resp.set_cookie("t2_cookie","cookie2")
    return resp

  然后提前放上測試用的各種代碼

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <script type="text/javascript" src="{% static 'js/jquery-3.2.1.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/jquery-cookie.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/my-session.js' %}"></script>
    <title>Title</title>
</head>
<body>
    <a href="goTestRender">跳轉到test頁面</a>
</body>
<script type="text/javascript">
    console.log("render cookie:",$.cookie("t1_cookie"))
    console.log("render session:",getSession("t1_session"))
</script>
</html>
index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
      {% load static %}
    <title>test table</title>
{#    <link rel="stylesheet" href="style.css">#}
    <!-- Delete ".min" for console warnings in development -->
    </head>
  <body>


<!-- 取消這個范圍內的django解析,從而解決django與vue語法沖突問題 -->
{% verbatim %}
  <script type="text/x-template" id="my_test_template">
  <table>
      <thead>
        <tr>
            <td v-for="t in title">
                {{ t }}
            </td>
        </tr>
      </thead>
      <tbody>
            <tr v-for="row in testData">
                <td v-for="d in row">{{ d }}</td>
            </tr>
      </tbody>
  </table>
</script>
{% endverbatim %}
    <!-- Vue.compent里的變量名=實例化時對應的變量名 -->
    <!-- Vue.compent里的變量名如果是駝峰命名兩個單詞的話需要用中划線分割 -->
    <my-test-table
        :title="myTitle"
        :test-data="myData"
    ></my-test-table>

  </body>


    <script type="text/javascript" src="{% static 'js/jquery-3.2.1.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/jquery-cookie.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/my-session.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/vue.js' %}"></script>
    <script type="text/javascript" src="{% static 'js/table.js' %}"></script>
</html>
test.html
function getSession(key) {
    result = undefined
    $.ajax({
        url:"getSession",
        type:"post",
        dataType:"json",
        data:JSON.stringify({key:key}),
        async:false,
        success:function (data) {
            result = data.result
        }
    })
    return result
}
my-session.js
Vue.component('my-test-table',{
    template:"#my_test_template",
    props:{
        title:Array,
        testData:Array,
    }
})

function getData()
{
    $.ajax({
        url:"test",
        type:"post",
        dataType:"json",
        data:JSON.stringify({
            testParamInteger:1,
            testParamString:"測試參數"
        }),
        success:function (data) {
            console.log(data)
            //  傳過來的參數自動被解析成對象了,無需轉換
            var myVue = new Vue({
                el:"my-test-table",
                data:{
                    myTitle:data.title,
                    myData:data.data
                }
            })

            //  測試cookie和session
            console.log("Ajax Cookie:"+$.cookie("t2_cookie"))
            console.log("Ajax Session:"+getSession("t2_session"))
        }
    })
}

$(function () {
    getData()
})
table.js

  測試結果

難點解釋:

  前端的my-session.js中的async:flase是為了取消異步,能讓返回值在獲取到結果之后再返回

  cookie獲取方法為引入jquery-cookie.js文件,調用$.cookie即可

  session的獲取方法為my-session中再次請求

  此外其他點都在注釋里了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2024 CODEPRJ.COM