第十章、模板详解 -- 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)


 

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