第十章、模板詳解 -- Ajax技術

  • Ajax(Asynchronous Javascript And XML),是一種進行頁面局部刷新數據的技術。
  • 傳統頁面在提交表單後,頁面會刷新,未保存的數據將會丟失
  • 使用Ajax技術,創建XMLHttpRequest對象發送表單請求,並利用JavaScript的DOM操作,可以實現對指定元素的修改,而不刷新頁面

實現步驟:

  • 修改topicdynamics.html文件

 

<a href="#" onclick="hyh()" id="hyh">
    換一換
</a>
  • 修改topicdynamics.js文件

 

function hyh() {
    form = document.getElementById('form1'); /* 獲得表單對象 */
    fd = new FormData(form);  /* 根據表單對象,創建formdata對象,其包含用戶提交的數據 */

    /*
        fd = new FormDate();
        fd.append( key1, value1);
        fd.append( key2, value2);
        ------------------------------
        def dohyh(request):
            value1 = request.POST.get(key1)
            value2 = request.POST.get(key2)
     */

    var xhr = new XMLHttpRequest();
    xhr.open('post', '/personal/dohyh/');
    xhr.send(fd);  /* 通過send函數將數據發給服務器 */

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200 || xhr.status == 304) {
                ret = JSON.parse(xhr.responseText);  /* 將json串轉成對象 */
                obj = document.getElementsByClassName('tiaozhuan');
                obj[0].innerHTML = ret.title1;
                obj[1].innerHTML = ret.title2;
            }
        }
    }
}
  • 修改urls.py文件

 

url(r'^dohyh/$', views.dohyh),
  • 修改views.py文件

 

def dohyh(request):
    username = request.POST.get('username')
    passwd = request.POST.get('passwd')

    print('---->' + username + ', ' + passwd)

    list = ['軍事', '音樂', '國內', '國際', '財經', '娛樂', '體育', 
            '互聯網', '科技', '遊戲', '女人', '汽車', '房產']

    i1 = random.randint(0, len(list) - 2)
    # i2 = random.randint(0, len(list))
    # i3 = random.randint(0, len(list))

    content = {
        'title1': list[i1],
        'title2': username,
        'title3': passwd,
    }

    ret = JsonResponse(content)  # 將對象轉成json串

    return HttpResponse(ret)

上傳頭像:

  • editPersonal.html

 

<form id="form1" method="post" enctype="multipart/form-data">
    <input type="file" name="photo" id="uploadphoto" onchange="douploadphoto()">
</form>

... ...

<div class="photo" id="photo" style="background-image: url('{{ user_photo }}')">
    <div class="camra"><i class="fa fa-camera fa-2x" aria-hidden="true"></i></div>
    <span class="xiugaizi" onclick="upload()">修改我的頭像</span>
</div>
  • editPersonal.js

 

function upload() {
    var obj = document.getElementById('uploadphoto');
    obj.click();
}

function douploadphoto() {
    form = document.getElementById('form1'); /* 獲得表單對象 */
    fd = new FormData(form);  /* 根據表單對象,創建formdata對象,其包含用戶提交的數據 */

    var xhr = new XMLHttpRequest();
    // xhr.withCredentials = true;
    xhr.open('post', '/personal/dohyhphoto2/');
    xhr.send(fd);  /* 通過send函數將數據發給服務器 */

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) {
            if (xhr.status == 200 || xhr.status == 304) {
                ret = JSON.parse(xhr.responseText);  /* 將json串轉成對象 */
                obj = document.getElementById('photo');
                obj.style.backgroundImage = "url('"+ret.user_photo+"')";
            }
        }
    }
}
  • urls.py

 

    url(r'^dohyhphoto2/$', views.dohyhphoto2),
  • views.py

 

def dohyhphoto2(request):
    s = request.session.get('personinfo')
    uid = s['user_id']

    # 根據id獲得對應的用戶對象
    p = PersonInfo.objects.get(user_id=uid)

    # 保存上傳的文件
    p.user_photo = request.FILES.get('photo')

    # 將上傳文件保存到DB
    p.save()

    # 將改變的頭像路徑寫入session
    s['user_photo'] = p.user_photo.url
    request.session['personinfo'] = s

    content = {
        'user_photo': p.user_photo.url,
    }

    ret = JsonResponse(content)

    return HttpResponse(ret)


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章