我想在我的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将从现有图形中删除。
下面是我用来响应GET请求的jquery,它在我的模板末尾:
<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-如何在不删除先前数据的情况下将数据添加到当前图形中。
发布于 2021-05-07 20:45:00
在哪里有你的评论:
$('#graph').html(data["current_graph"])
发布于 2022-02-16 03:57:17
您可以使用以下命令将内容添加到div:
$('#theDiv').prepend('<img id="theImg" src="theImg.png" />')在本例中,我在div中附加了一个图像。ajax调用中的内容类似于:
$.ajax({
url : "{% url 'url_to_call' %}",
type : 'get',
data : {
somedata : $('#somedata').val()
},
success: function(response){
$( "#the-div" ).prepend('<img id="id" src="theImg.png" />')
}
});https://stackoverflow.com/questions/65273866
复制相似问题