2013-10-02 22 views
1

我已經選了這個這個,但想如果我可以,我會伸出一些建議,我是相當新的AJAX。DJANGO jQuery的/ AJAX GET「的HttpResponse」 JSON

對,我使用的Django框架,我發佈的數據到服務器,這很好,然後接收一些數據回調函數,它的工作,雖然我想這是JSON格式,所以我可以填充表格。目前它要麼以純文本格式呈現,要麼瀏覽器要求我下載json數據,這意味着某些東西不能很好地捕捉$ .get部分。我的代碼是:

#views.py 

    if request.POST: 
    est_show = login_a.test() 
    return HttpResponse(est_show, content_type='application/json') 


    <!--JQUERY/AJAX--> 
    <script type="text/javascript"> 
    $(document).on("submit","#these_choices",function (event) { 
    var data_form = $('#these_choices').serialize(); 


    if(data_form) { 
    $.ajax({ 
     type: "POST", 
     url: "{% url Create_this %}", 
     data: {'test':'test','csrfmiddlewaretoken': '{{ csrf_token }}'}, 
     cache:false, 
     success: function(){ 
     jQuery(document).ready(function ($) { 
     $.get('{% url Create_this %}', function(data) { 
      alert(data[0]); 
      });}); 

       }, 
     error: function(){ 
     alert('error !!!!'); 
     } 

       });} 
else { 
    alert('error elsewhere'); 
} 

event.defaultPrevented(); //not running PreventDefault returns json using defaultPrevented returns json and doesnt render anything when this is blanked out... 
return false; 
    }); 
    </script> 

它也似乎警報(數據[0])在瀏覽器正在接收JSON數據之前被跑。任何建議將被認真考慮?

非常感謝

回答

0

嘗試在HttpResponse設置mimetypeapplication/json。當你不Ajax請求指定dataType,JQuery的自動嘗試根據響應的MIME類型來推斷它。

return HttpResponse(est_show, mimetype='application/json') 

或者,你可以將dataType設置爲json告訴jQuery來期待JSON。