2016-01-23 76 views
0

我是新来的Django和AJAX,我试图发送一个下拉列表的ID到Django视图与ajax POST。然后在查询集过滤器中使用此ID,以基于该ID的AJAX返回该行。我陷入了将查询过滤器应用到查询集的问题,因为它好像是发布了ID,然后是一个带有None的变量。当我打印到控制台在POST我得到的ID发送的变量,其次是没有,例如:Django返回没有请求后.POST.get

1748 
None 

我的HTML是:

<select id="drugSet"> 
{% for dose in dose_set %} 
<option id="{{ dose.pubmed_id }}">{{ dose.drug_name }}</option> 
{% endfor %} 
</select> 
<span id="drugName"></span> 

的Javascript:

function NeedDrugInformation() { 
      var elementID = document.getElementById("drugSet"); 
      var strUser = elementID.options[elementID.selectedIndex].id; 

      $.ajax({ 
       type: "POST", 
       url: "drugsanddoses/", 
       dataType: "text", 
       async: true, 
       data: { csrfmiddlewaretoken: '{{ csrf_token }}', drugID: strUser }, 
      }); 

      $.ajax({ 
       type: "GET", 
       url: "drugsanddoses", 
       dataType: "text", 
       async: true, 
       data: { csrfmiddlewaretoken: '{{ csrf_token }}' }, 
       success: function (json) { 
        $('#drugName').html(json.drugInfo); 
        // $('.ajaxProgress').hide(); 
       } 
      }) 
     } 

意见.py:

def drugsanddoses(request): 

    drugIdentifier = request.POST.get('drugID') 

    print(drugIdentifier) 

    drugInfo = RiskCalculator.objects.values('drug_name', 'l_dose', 'h_dose', 'risk', 'pubmed_id', 'updated') 

    response_data = {} 

    try: 
     response_data['drugInfo'] = str(drugInfo) 
    except: 
     response_data['result'] = 'No details found' 
     response_data['message'] = 'There is currently no information in the database for this drug.' 


    return HttpResponse(json.dumps(response_data), content_type="application/json") 

回答

2

您正在制作两个Ajax请求uests;一个是POST,其中存在ID,另一个是GET,其中ID不存在,因此它打印无。我真的不明白为什么你提出了两个请求,但这就是你正在做的。

+0

我想将ID发送到视图,并让它返回数据库中的关联行。我可以使用单个POST执行此操作吗? – GeeJay

+0

当然可以。您只需在执行POST的'ajax'调用上定义'success'函数。 –

相关问题