Ajax在views.py django中发送数据两次 [英] Ajax sending data twice in views.py django
问题描述
我在index.html
中有这个form
,在单击一个名为.graph-btn
的按钮时有两个提交按钮
我正在使用jquery和ajax将数据从form
发送到Django.
I have this form
in index.html
and two submit button on clicking on one button named .graph-btn
I m using jquery and ajax to send data from form
to Django.
代码:
index.html
<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>
在这里,我想从名为.comp_name
的th
行中获取数据,并将数据传递给Django中的views.py.
有问题的是Ajax.
here I want to take data from th
row named .comp_name
and pass the data to views.py in Django.
There is problem is Ajax.
views.py
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')
我正在使用Print语句检查是否一切正常. 问题是,当我单击.graph-btn
时,它会抛出两个迭代值.第一个是右边,但是第二个是None
.
此处
I m using Print statement to check if everything is fine. the problem is that when I click on .graph-btn
it throws me two iterative values. First one is the right but the second one is None
.
here
请帮帮我.
推荐答案
您不应使用jquery类选择器.使用id选择器("#id").现在发生这种情况是因为您只有一个带有"graph-btn"类的按钮.只需为for循环中的按钮分配ID({%,a,b占股票%})
you shoudn't use jquery class selector. use id selector("#id"). Now it happens because you have more then one button with 'graph-btn' class. Just assign IDs to your buttons in for loop ( {% for a,b in stocks %})
这篇关于Ajax在views.py django中发送数据两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!