2016-12-08 3 views
0

私のHTMLからDjangoバックエンドにIDの配列を送り、コンテキストとして対応するクエリーセットを返したいと思います。 これまでのところ、私は次のコードを持っていますが、それだけでは動作しませんし、私は任意の解決策を見つけることができませんでした:Django AJAX GET list from context

HTMLフォーム:

<form id="select_form" method="get"> 
<button type="submit" id="submit_selection_button" .btn-lg">Submit</button> 
</form> 

のjQuery:

<script type="text/javascript"> 
$(document).ready(function() { 
$("#submit_selection_button").click(function() { 
    selectedFoo = [1,2]; 
    $.ajax({ 
    type: 'GET', 
    url: '/', 
    data: {'selected_foo[]': selectedFoo}}); 
    }); 
    }); 
</script> 

ジャンゴビュー:

class FooBar(TemplateView): 
    def dispatch(self, request, *args, **kwargs): 
     self.request = request 
     return super(FooBar, self).dispatch(request, *args, **kwargs) 

    def get_queryset(self): 
     return super(FooBar, self).get_queryset() 

    def get_context_data(self, **kwargs): 
     context = super(FooBar, self).get_context_data(**kwargs) 

     selected_foo = [] 
     if(self.request.method == "GET"): 
      selected_foo = self.request.GET.getlist('selected_foo[]') 

     if(selected_foo): 
      bar_results = Bar.objects.filter(id__in=selected_foo) 
     else: 
      bar_results = Bar.objects.none() 

     context = { 
      'bar_results': bar_results, 
     } 
     return context 

foobar = FooBar.as_view() 

私の問題はGET要求を受け取ることですが、 "selected_foo"を使用しようとすると空白になります。私はおそらくjQueryの部分で間違いを犯しましたが、私は初心者であり、私が間違っていたかどうかはわかりません。 私を助けて説明してください。ありがとう

+0

まだ動作しませんが... – JohnDro

+0

変更 'データ:{ 'selected_foo []':selectedFoo}} ); 'to' data:{'selected_foo':selectedFoo}}); ' –

+0

私はすでにそれを試みました。まだ変更はありません。私の見解では、それは常にelseステートメントに行きます。私はそのフォームについては分かりません。メソッド= "get"とアクション= ".."があるはずですか? – JohnDro

答えて

0

注意するべきことのカップル。 Ajaxを使用する場合は、JSONレスポンス(Content-typeがapplication/jsonのHTTPレスポンス)を返す必要があります。第二に、AJAX呼び出しを行うときは、POSTを使用して、request.bodyを使用してJSONを渡すことをお勧めします。 YMMV。

にあなたのjQueryを更新します。

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#submit_selection_button").click(function() { 
      selectedFoo = [1,2]; 
      $.post('/', {'selected_foo': selectedFoo}}); 
     }); 
    }); 
</script> 
にあなたのビューに変更し

class FooBarAjax(View): 
    def post(self, request, *args, **kwargs): 
     selected_foo = json.loads(request.body) 
     bar_results = Bar.objects.none() 
     if selected_foo: 
      bar_results = Bar.objects.filter(id__in=selected_foo) 
     return JsonResponse({ 
      'bar_results': [{ 
       # serialize Bar to a dict here so that you can pass it 
       # back as JSON 
      } for result in bar_results] 
     })