【发布时间】:2021-03-24 04:45:24
【问题描述】:
我想在我的 Django 项目中使用 ajax 更新我的绘图图。这是我到目前为止所尝试的。 我正在按照this 指南进行操作,而且我对 jquery 和 ajax 完全陌生。
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('smartflow/ajax/updategraph', views.updategraph, name = "updategraph")
]
在 views.py 中,我定义了一个 updategraph 函数(视图)来完成 GET 请求的工作。
def updategraph(request):
df_georgian = get it from a csv file for example
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
coding = request.GET.get('coding')
if coding:
trace2 = go.Scatter(x=df_georgian.index,
y=df_georgian.loc[:, df_georgian.columns[2]],
mode='lines',
name='2')
fig_new = go.Figure(data=[trace2])
plot_div_new = plot(fig_new,
config=config,
output_type='div')
data = {
'my_data':plot_div_new
}
return JsonResponse(data)
else:
return redirect('smartflow')
这是我的模板:
<div class="container">
<div class="row">
<div class="col-12 col-sm-12 col-md-12 col-lg-12 col-xl-12 mx-3 px-0 mt-5 pt-5" id="graph" >
{% autoescape off %}
{{ new|safe }}
{% endautoescape %}
</div>
<div class="col-12">
<div>
<input type="checkbox" id="coding" name="interest" value="coding" onclick = "myfunction()">
<label for="coding">Coding</label>
</div>
</div>
</div>
</div>
我希望,如果选中了coding 复选框,则图表会将trace2 添加到自身,当取消选中时,trace2 将从现有图表中删除。
这是我的 jquery 来响应模板末尾的 GET 请求:
<script type = "text/javascript">
$("#coding").change(function () {
if (document.getElementById('coding').checked) {
alert("checked");
var current_graph = $('#graph').val();
$.ajax({
url: "{% url 'updategraph' %}",
data: {
'current_graph': current_graph
},
dataType: 'json',
success: function (data) {
// $('#graph').val() = current_graph; //Here is my question?!?!?!?!?!??!?!?!?!
alert(response);
}
});
} else {
alert("unchecked");
}
});
当我选择 coding 时,我在 chrome 控制台中收到以下错误:
GET http://127.0.0.1:8000/smartflow/ajax/updategraph?current_graph= 500 (Internal Server Error) jquery-3.5.1.min.js:2
send @ jquery-3.5.1.min.js:2
ajax @ jquery-3.5.1.min.js:2
(anonymous) @ (index):1683
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2
在我的js代码的成功函数中($('#graph').val() = data; //这是我的问题?!?!?!?!?!??!?!?!? !) 部分:
1- 我不知道如何获取我在views.py 中返回的my_data 并将其放入具有#graph id 的div 中。
2- 如何将数据添加到当前图表而不删除以前的图表。
【问题讨论】:
-
您好,当您聚焦复选框未点击提交按钮时,您的事件将被调用。做一件事,您可以检查复选框查看您的
network tab->XHR查看您的ajax请求详细信息。此外,将alert(response)放入成功函数中,看看这是否显示以及它带来了什么。 -
@Swati 你是对的,我的事件不对。我更新了问题,我还更新了事件并使用
alert对其进行了测试,它工作得很好,但是alert(response);什么也没显示,这是否意味着我的 ajax 调用没有发生? -
它发生了,但是你有服务器错误。在这里,
#graph不是 div 输入,我认为您需要传递复选框值,只需使用$(this).val()获取它。另外,您使用request.GET.get('coding')从 ajax 获取价值 .. 那不应该是request.GET.get('username')吗?跨度> -
@Swati
network tab->XHR中的请求状态为500。所以我的ajax请求没有发生,我做错了什么? -
@Swati 我的错,我忘记更新变量名称了。请再次检查代码。我使用
#graph来获取当前图形,然后将从ajax 接收到的数据添加到其中。#coding是复选框的 id,ajax 调用有什么要保存的吗?