簡體   English   中英

Django&ajax:控制Ajax查詢返回的“數據”

[英]Django & ajax : control the 'data' returned by Ajax query

我有兩個字段,具體取決於一個字段。 到現在為止,我可以使一個字段依賴,但不能同時依賴兩個字段,因為我不知道如何控制Ajax的數據變量。

 $("#id_type1").change(function () {
  var url = $("#personForm").attr("data-tiers-url");  // get the url of the `load_cities` view
  var typeID = $(this).val();  // get the selected country ID from the HTML input
//  alert(countryId)
  $.ajax({                       // initialize an AJAX request
    url: url,                    // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
    data: {
      'tiers': typeID       // add the country id to the GET parameters
    },
    success: function (data) {   // `data` is the return of the `load_cities` view function
      alert(data)
      $("#id_tiers").html(data);
      // replace the contents of the city input with the data that came from the server
    }
  });
});

這是返回包含樹變量的數據的視圖:

def load_tiers(request):
    tiers_id = request.GET.get('tiers')
    print(tiers_id)
    tiers = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    #print(cities)
    frs="Fournisseur";
    clt="1";
    if tiers_id=="Fournisseur":
        frs = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    elif tiers_id=="client":
        clt = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    return render(request, 'appOne/city_dropdown_list_options.html', {'tiers': tiers,'frs':frs,'clt':clt})

我需要控制以下data$("#id_tiers").html(data); #id_tiersdata['frs']的值data['frs']而不是'tiers','frs','clt'

這是什么數據包含:

在此處輸入圖片說明

您能否幫助我實現這一目標,因為我是Ajax和js的新手。

我是否可以建議您更改Python端點或創建一個新的端點,以便僅將JSON返回給AJAX調用? 解析HTML以獲取所需值比將響應作為JSON發送要困難得多。

def load_tiers_json(request):
    tiers_id = request.GET.get('tiers')
    tiers = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    frs="Fournisseur";
    clt="1";
    if tiers_id=="Fournisseur":
        frs = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    elif tiers_id=="client":
        clt = operation_Bancaire.objects.all().filter(type_tiers=tiers_id)
    return JsonResponse({'tiers': tiers,'frs':frs,'clt':clt})

然后在您的AJAX調用中,從返回的data獲取所需的密鑰:

$("#id_type1").change(function () {
  var url = $("#personForm").attr("data-tiers-url");  // get the url of the `load_cities` view
  var typeID = $(this).val();  
  $.ajax({                       
    url: url,                    
    data: {
      'tiers': typeID     
    },
    success: function (data) {   
      $("#id_tiers").html(data.frs);
    }
  });
});

當然,您將需要更改Django urls.py以公開此新端點,並在JavaScript調用中更改url值以使用新端點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM