【问题标题】:Trouble with Ajax post in DjangoDjango 中的 Ajax 帖子出现问题
【发布时间】:2013-12-20 20:23:41
【问题描述】:

我需要三个相关的下拉菜单。当用户选择第一个菜单(市场环境)时,我需要 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));
            }
        }

【问题讨论】:

  • 你应该使用.text(item.Name)。 Html 会覆盖&lt;option&gt;&lt;/option&gt;。如果应该尝试this library (jquery.chained.js),它将帮助您更轻松地编写链接选择代码。

标签: javascript jquery python ajax django


【解决方案1】:

您没有发送 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");
    }
})

【讨论】:

  • 谢谢你成功了!如果我需要将该数据添加到第二个下拉菜单中,代码将是:success: function(data) { $('#id_curr').append(data); },
  • 我编辑了我的原始帖子,以便更容易阅读我关于将数据添加到我的第二个菜单的问题。
  • @vdesai 当您将请求中的 csrf_token 发送到 django 时,也许您可​​以考虑删除 csrf_exempt 装饰器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-21
  • 1970-01-01
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-28
相关资源
最近更新 更多