繁体   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