Python Ajax在views.py django中发送数据两次

Python Ajax在views.py django中发送数据两次,python,jquery,django,ajax,django-views,Python,Jquery,Django,Ajax,Django Views,我在index.html中有这个表单,单击一个名为.graph btn的按钮时有两个提交按钮 我使用jquery和ajax将数据从表单发送到Django 代码: index.html 我用打印报表检查是否一切正常。问题是,当我点击.graph btn时,它会抛出两个迭代值。第一个是正确的,但第二个不是。 请帮帮我 您不应该使用jquery类选择器。使用id选择器“id”。现在它发生了,因为您有一个以上的按钮与'graph btn'类。只需将ID分配给for循环中的按钮{%a,b在stocks%

我在index.html中有这个表单,单击一个名为.graph btn的按钮时有两个提交按钮 我使用jquery和ajax将数据从表单发送到Django

代码: index.html

我用打印报表检查是否一切正常。问题是,当我点击.graph btn时,它会抛出两个迭代值。第一个是正确的,但第二个不是。


请帮帮我

您不应该使用jquery类选择器。使用id选择器“id”。现在它发生了,因为您有一个以上的按钮与'graph btn'类。只需将ID分配给for循环中的按钮{%a,b在stocks%}

您能用代码解释一下吗?还有,这个类中有不止一个按钮。你在你的页面上看到了多少具有“视图图”值的按钮?非常感谢你的努力,但它仍然是一样的。有50个按钮具有不同的{a},所以你的javascript中有50个ajax调用
 <form action="{% url 'Graph' %}" method="post">
                        {% csrf_token %}
                <table class="table table-striped table-dark" cellspacing="0">
                    <thead class="bg-info">
                    <tr>
                        <th>Company's Symbol</th>
                        <th>Current Price</th>
                        <th>View Current chart</th>
                        <th>Action</th>
                    </tr>
                    </thead>
                    <tbody>
                    {% for a,b in stocks %}
                    <tr>
                        <th scope="row" class="comp_name">{{ a }}</th>
                        <td>{{ b }}</td>
                        <td>
                            <input type="submit" class="btn graph-btn" name="_graph" value="View Graph">
                        </td>
                        <td>
                            <input type="submit" class="btn predict-btn" formaction="{% url 'Graph' %}" name="_predict" value="Predict Closing Price">
                        </td>
                    </tr>
                    {% endfor %}
                    </tbody>
                </table>
                </form>
<script>
    $(".graph-btn").click(function(e) {
    var $row = $(this).closest("tr");
    var $text = $row.find(".comp_name").text();
    var name = $text;
    console.log(name);
    $.ajax({
        type:'POST',
        dataType: "json",
        url:'{% url 'Graph' %}',
        data:{
            'text': name,
            'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(),
        },
        success:function(json){
        },
        error : function(xhr,errmsg,err) {
        }
    });
});
</script>
def graph(request):
    if request.method == 'POST':
        print("testing....")
        print(request.body)
        print(request.POST.get('text'))
        name = request.POST.get('text')
        context = {
            'name': name,
        }
        print(context)
        return render(request, 'StockPrediction/chart.html')
    else:
        return render(request, 'StockPrediction/greet.html')