簡體   English   中英

Django中的Ajax發布問題

[英]Trouble with Ajax post in Django

我需要三個相關的下拉菜單。 當用戶選擇第一個菜單(市場環境)時,我需要ajax將該選擇發送到django中的視圖中,以便我可以查詢SQL以獲取貨幣列表並填充第二個列表。 在螢火蟲中,我不斷收到以下錯誤:

MultiValueDictKeyError at /Tplots/ajax_curr/"'mkt'"

我還注意到我的帖子是空的,所以我認為我的Ajax代碼出了點問題,而且我不確定有什么問題。 任何幫助都會很棒。

HTML

<script type="text/javascript">
$(document).ready(function get_currency(){
$('#id_mkt').on('change', function(e) {
    e.preventDefault();
    $.ajax({
        type:"POST",
        url: "/Tplots/ajax_curr/",
        datatype: "json",
        success: function(data) {
            alert(data);
        },
        error:function(){
            alert("failure");
        }
    })
 })
   })
</script>

<div align="center">
<h1>Swap Curves</h1>
<form action="{% url 'Tplots:swapFig' %}" method = "post">
{% csrf_token %}
{{form.mkt}}
{{form.curr}}
{{form.horizon}}
<input type = "submit" value="Go To" />
</form>

view.py

@csrf_exempt
def ajax_curr(request): 
    if request.is_ajax():
        selected_mkt = MktEnv.objects.get(mkt=request.POST['mkt'])
        #selected_mkt = request.POST.get('mkt','')
        conn = pyodbc.connect('abcd')
        cursor = conn.cursor()
        sql_raw = r'''
            select currency from market_env_detail
            where mkt_env_id=%s
            and idx = 1''' % (selected_mkt)
        cursor.execute(sql_raw)
        xx = cursor.fetchall()
        currencyL = []
        for items in xx:
            x = str(items[0])
            currencyL.append(x)
        curr = list(set(currencyL))
    json = simplejson.dumps(curr)
    print json
    return HttpResponse(json, mimetype="application/json")

forms.py

class CurrencyForm(forms.Form):
   Env_Choices = [('', '-- Choose a Environment --'), ] + [(m.mkt, m.mkt) for m in MktEnv.objects.all()]
   Curr_Choices = [('', '--Choose a Currency --'),]+[(c.curr, c.curr) for c in CurrencyAjax.objects.all()]
   Horizon_Choices = [('', '--Choose a Horizon --'),] +[(h.hid, h.hid) for h in HorIdAjax.objects.all()]
   mkt = forms.ChoiceField(choices=Env_Choices)
   curr = forms.ChoiceField(choices=Curr_Choices)
   horizon = forms.ChoiceField(choices=Horizon_Choices)

編輯:

我正在嘗試使用此成功函數將數據放入第二個下拉列表,但我的所有值都為空白。 不知道為什么。

success: function(data) {
            for(var i =0; i<data.length; i++) {
                var item=data[i];
                $('#curr').append(
                    $("<option></option>").val(item.Id).html(item.Name));
            }
        }

您不發送POST數據。 您缺少data參數。

var data = $(this).parents('form').serialize();

$.ajax({
    type:"POST",
    url: "/Tplots/ajax_curr/",
    data: data,
    datatype: "json",
    success: function(data) {
        alert(data);
    },
    error:function(){
        alert("failure");
    }
})

暫無
暫無

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

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