2014-01-07 18 views
3

我是Django的新手,並且試圖獲取從Ajax發送來的變量以便在Django視圖中使用。我的觀點:使用Ajax調用來更新Django視圖

def index(request): 
    if (request.is_ajax()): 
    username = request.GET['user'] 
    else: 
    username = '' 
    context = {'user':username} 
    return render(request, 'index.html', context) 

和AJAX:

$.ajax({ 
    url: '/index/', 
    type: 'GET', 
    data: {user: response.name, page: page} 
}); 

我的問題是,username不會在視圖更新,基於Ajax調用。我知道ajax調用工作正常,因爲在查看網絡響應​​時,它正在傳遞適當的更新用戶名。

我相信發生的事情是視圖被加載,然後ajax調用發生並更新用戶名,但視圖不被重新呈現,因此不會改變。我已經嘗試在獲取用戶名後進行另一次渲染,但是這並沒有改變任何內容,並且我也爲處理ajax調用提出了單獨的視圖,但這似乎也不起作用,因爲視圖總是在沒有Ajax請求的情況下加載是真的。

這是怎麼得到這個工作?謝謝你的幫助。

+0

你從ajax響應中得到什麼?你在做什麼?如果你在你的ajax請求中添加'complete:function(resp){...}',那麼函數裏面的'resp.responseText'是什麼? – jproffitt

+0

對不起,還有一個ajax的新手。如果我console.log響應文本,它會使用新的'username'記錄更新後的索引頁面。那麼我應該重新加載成功的頁面嗎? – mcw

+0

你可能會用新的DOM替換DOM。但這是一種效率極低的方式。你真的需要返回用戶名,並更新。看看布蘭登的答案。在那裏他有'console.log(json.user);'做一些像$('#username')。html(json.user)' – jproffitt

回答

6

如果您打算通過Ajax返回JavaScript可用於更新DOM的響應,則需要返回HttpResponse,最好以JSON格式返回,該格式可以傳遞給$ .ajax調用中的處理程序。例如:

import json 

from django.contrib.auth.models import User 
from django.http import HttpResponse 
from django.shortcuts import render 


def index(request): 
    if request.is_ajax(): 
     username = request.GET.get('user', '') 
     user = User.objects.get(username=username) 

     # do whatever processing you need 
     # user.some_property = whatever 

     # send back whatever properties you have updated 
     json_response = {'user': {'some_property': user.some_property}} 

     return HttpResponse(json.dumps(json_response), 
      content_type='application/json') 

    return render(request, 'index.html', {'user': ''}) 

然後,在JavaScript,你可以這樣做:

$.get('/index/', {user: response.name, page: page}, function(json_response) { 
     console.log(json_response.user.some_property); 
}); 

用這種方法,一個正常的GET請求您的視圖返回渲染HTML模板。對於Ajax請求,視圖將返回JSON格式的HttpResponse,並將其傳遞給jQuery $ .get調用中的回調。

+0

我收到一個'response'未定義的錯誤,來自'json.dumps(response)'行。 – mcw

+0

對不起,這是我的錯。我對響應變量的名稱做了一些重構。我已經爲你更新了我的答案。 – Brandon

+0

太棒了,它確實更新了DOM。但有什麼辦法可以在視圖中使用更新的用戶名?就像以某種方式獲得該值並將其用於索引視圖。實際應用中的索引正在以用戶名作爲參數運行查詢,因此我想知道如何爲以後的查詢獲取此新用戶名。感謝您一直以來的幫助! – mcw

2

要通過Ajax調用將數據發送到django視圖,您需要向Form添加數據,然後發送ajax請求。

例子: 我view.py:

def index(request): 
""" 
View function to handle Ajax request for image Link. 
:param request: Ajax request data. 
:return: image URL. 
""" 
if request.is_ajax(): 
    try: 
     username = request.POST['username'] 
     # perform operations on the user name. 

    except: 
     e = sys.exc_info() 
     return HttpResponse(e) 
    return HttpResponse(sucess) 
else: 
    raise Http404 

我的模板的index.html

<html> 
 
    <head> 
 
     <title>Index</title> 
 
     <script> 
 
     $(document).ready(function() { 
 
      $('#btnSubmit').click(function() { 
 
       var data = new FormData(); 
 
       var username = $('#id_username').val() 
 
       data.append('username', username); 
 
       $.ajax({ 
 
        type: 'POST', 
 
        url: 'getuser/', 
 
        data: data, 
 
        processData: false, 
 
        contentType: false, 
 
        success: function(json) { 
 
         alert(json); 
 
        } 
 
       }) 
 
      }); 
 
     }); 
 
        
 
     </script> 
 
    </head> 
 
    <body> 
 
     <h1>Index</h1> 
 
     User name: <input type="text" name="fname" id="id_username"> 
 
     <input type="submit" id ="btnSubmit" name="submit" value="Send Test Push"> 
 
    </body> 
 
</html>

這一點,你需要添加AJAX調用鏈接到URL中後的.py。