Javascript Django:在Ajax调用中检索所选下拉选项的私钥

Javascript Django:在Ajax调用中检索所选下拉选项的私钥,javascript,django,Javascript,Django,我有两个这样的模型: class ScenarioMarket(models.Model): title = models.CharField(max_length=50, default="") description = models.TextField(default="") b = models.IntegerField(default=100) cost_function = models.IntegerField(default=0) open

我有两个这样的模型:

class ScenarioMarket(models.Model):
    title = models.CharField(max_length=50, default="")
    description = models.TextField(default="")
    b = models.IntegerField(default=100)
    cost_function = models.IntegerField(default=0)
    open = models.BooleanField(default=True)

    def __str__(self):
        return self.title[:50]

    def get_absolute_url(self):
        return reverse('market_detail', args=[str(self.id)])

class Scenario(models.Model):
    description = models.TextField(default="")
    current_price = models.DecimalField(max_digits=5, decimal_places=2, default=0.00)
    share = models.IntegerField(default=0)
    market = models.ForeignKey(
        ScenarioMarket, 
        on_delete=models.CASCADE,
        related_name='scenarios', 
        default=None)

    def __str__(self):
        return str(self.description)
在我的模板中,我有一个下拉菜单,可以循环(描述)相关场景市场上的所有可用场景,每个选项都将相关场景的
pk
作为其值:

<form action="" method="GET" id="scenario-dropdown">
{% csrf_token %}
    <select>
        {% for description in scenariomarket.scenarios.all %}
        <option value="{{ description.id }}">
            {{ description }}
        </option>
        {% endfor %}
    </select>
</form>
但是在控制台中,我得到了
未捕获的TypeError:cannotreadproperty'value'of null
,因此它显然不起作用-很可能与
有关


我做错了什么?

您在这里基本上犯了两个错误:

  • 您应该将
    id=…”
    添加到
    标记,而不是
    标记;及
  • 您在
    id
    中输入了一个错误:它应该是
    scenario\u下拉列表
    ,而不是
    scenario dropwdown
  • 您可以将模板修复为:

    <form action="" method="GET">
    {% csrf_token %}
        <select id="scenario-dropdown">
            {% for description in scenariomarket.scenarios.all %}
            <option value="{{ description.id }}">
                {{ description }}
            </option>
            {% endfor %}
        </select>
    </form>
    
    {%csrf_令牌%}
    {%用于scenariomarket.scenarios.all%中的描述]
    {{description}}
    {%endfor%}
    
    并使用以下命令在JavaScript中进行查询:

    var scenario_id = document.getElementById("scenario_dropdown").value

    var scenario\u id=document.getElementById(“scenario\u dropdown”).value
    选择项没有id,表单的id带有连字符
    -
    ,而不是下划线。您输入了一个打字错误(这是
    场景下拉列表
    )。请注意,这将为您提供表单,而不是
    输入。@WillemVanOnsem啊,当然!修复打字错误并在
    中添加
    id
    ,成功了。谢谢你的快速回复!
    var scenario_id = document.getElementById("scenario_dropdown").value