【发布时间】:2019-10-20 06:43:13
【问题描述】:
我使用 ajax 将输出渲染到下面的 HTML 元素。
<p class="result-box" id="result-box">The result is : <br><strong id="result"></strong></p>
渲染第一个输入请求的结果时一切正常。 当我更新我的输入时,控制台会更改并打印所需的数据,但包含文本的网页不会更改。
我在下面的第二次以上刷新时得到Cannot read property 'setAttribute' of null at canvas_and_plot,如果我删除setAttribute,我得到Cannot read property 'getAttribute' of null at canvas_and_plot。
$(document).on('submit','#cat_select',function(e){
e.preventDefault();
$.ajax({
type:'POST',
url:'/cat_select',
data:{
l2:$('#l2').val(),
l3:$('#l3').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
},
success: function server_response(response) {
const r = JSON.parse(response);
console.log(r); //updated
var cat_result = r.cat_result;
console.log(cat_result[0]) //updated
var text=$('<i></i>');
$.each(cat_result, function(idx, value) {
text.append('<id="result'+idx+'">' + cat_result[idx][0]+ '<br>'); //even the text output are not updated
text.append('<canvas id="canv_'+idx+'" width="200" height="200"></canvas><br>');
});
$('#result').replaceWith(text);
$.each(cat_result, function(idx, value) {
canvas_and_plot(idx,cat_result[idx][9],cat_result[idx][10],cat_result[idx][11])});
}
function canvas_and_plot(idx,a,b,c) {
var canv = document.getElementById('canv_'+idx);
canv.setAttribute('id', 'canv_'+idx);
var C = document.getElementById(canv.getAttribute('id'));
//plot...
}
我尝试添加cache: false 并向url 添加随机数,但它们都不起作用。
为什么只在第一次请求后出错?我怎样才能解决这个问题?谢谢
【问题讨论】:
-
我是否理解正确,当您再次提交表单时,您会收到错误消息?
标签: javascript jquery django ajax