2013-08-24 29 views
2

我想在Django框架中發出ajax請求。但是,我沒有通過從json中的客戶端獲取數據。它適用於我不使用Json的情況。 如果我在ajax中使用dataType:'json'與{'a':'value'},我無法在view.py中得到它,結果是什麼都沒有... 但是,如果我使用數據: $(this).serializeArray()在ajax中我可以得到request.POST的結果。但是,我真的需要自定義我的數據併發送到我的view.py其他數據,而不是來自表單的數據。我想發送{'a','mydata','form':myformdata} ... 有沒有辦法做到這一點?Json在Ajax中無法使用Django

模板:

<form id="ajax2" action="/seghca/test-post/" method="post">{% csrf_token %} 
Nom : <input type="text" name="nom" value="" id="nom"/><br/> 
prenom : <input type="text" name="prenom" value=""/><br/> 
<input type="submit" value="Envoyer"/> 
</form> 


<div id="result"></div> 

的javascript:

$(document).ready(function(){ 


     // POST AJAX 
     $("#ajax2").submit(function() { 
     var urlSubmit = $(this).attr('action'); 

     var data = $(this).serializeArray(); 
     data.push({ 
       key: "keyName", 
       value: "the value" 
      }); 
     $.ajax({ 
      type: "POST", 
      url: urlSubmit, 
      dataType: "json",    
      data  : data,//$(this).serializeArray(), 
      success: function(response){ 
       var json_response = JSON.parse(response); 
        // now get the variables from the json_response 
        $('#result').html(json_response.html); 
      } 
     }); 
     return false; 
    }); 

    }); 

view.py(Ajax的啓動test_post視圖,HOME2是表現公式的視圖):

from datetime import datetime 
from django.http import HttpResponse, Http404 
from django.shortcuts import redirect, render 
from seghca.models import Article 


from django.shortcuts import render_to_response 
from django.http import HttpResponse 
from django.template import RequestContext 
from django.views.decorators.csrf import csrf_exempt 
import json 

def home2(request): 
    return render_to_response('seghca/form.html', context_instance=RequestContext(request)) 

@csrf_exempt 
def test_post(request): 
    data = {'html': request.POST['key']} 
    return HttpResponse(json.dumps(data), mimetype="application/json") 
+0

的可能重複[Django的Ajax的jQuery的不取數據(http://stackoverflow.com/questions/18397100/django-ajax-jquery-does-not -fetch-the-data) –

回答

1

您正在使用ajax視圖,您應該從json窗體的視圖中返回數據:

data = {'html': request.POST['input']} 
return HttpResponse(json.dumps(data), mimetype="application/json") 

其次,有必要來分析第一個客戶端上的迴應:

success: function(response){ 
    var json_response = JSON.parse(response); 
    // now get the variables from the json_response 
    $('#result').html(json_response.html); 
} 

第三,如果你需要傳遞的表單數據與更多的一些信息,以及你可以這樣做:

var data = $(this).serializeArray(); 
data.push({ 
    key: "keyName", 
    value: "the value" 
}); 

四,你缺少csrf令牌。

+0

我修改了我的代碼,但是它沒有解決問題,views.py沒有收到任何東西!看來Django不希望得到json ... – user1731699

+0

請確保您在發佈數據中也傳遞了csrf令牌。 –

+0

我用裝飾器編輯過(它正確嗎?),但它仍然不起作用。 – user1731699

0

變化data: data,data: {'data': JSON.stringify(data)},

,你就可以通過POST['data']在Django訪問您的數據的序列化版本。請記住,如果你想在django中使用它,你必須反序列化它,例如json.loads(POST['data'])

0

我有你的相同需求。我的解決辦法是:

Ajax請求:

var posturl = $('#'+formid).prop('action'); 

$.ajax({ 
     async:false, 
     type: "POST", 
     dataType: "json", 
     contentType: "application/x-www-form-urlencoded", 
     url : posturl, 
     data : $('#'+formid).serialize() + '&mode=ajax', //&mode=ajax is my custom data 
     success:function(response){    

       console.log(response); 
         alert(response.message); 

     }, 
     timeout:10000 
}); 

在views.py:

 data = {'error': '0', 'message': 'all was ok'} 
     return HttpResponse(json.dumps(data), mimetype="application/json") 

以上應爲你工作。我的測試是使用Django 1.6和Python 2.7.5