我使用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
添加随机数,但是它们都不起作用。
为什么在第一个请求之后只有错误?我怎样才能解决这个问题?谢谢
答案 0 :(得分:1)
其不变的原因是您用接收到的数据替换了块#result
。
$('#result').replaceWith(text);
之后,您将看到一棵看起来像这样的dom树:
<p class="result-box" id="result-box">
The result is : <br>
<i>
<id="result123">...<br>
<canvas id="canv123" width="200" height="200"></canvas><br>
<id="result321">...<br>
<canvas id="canv321" width="200" height="200"></canvas><br>
</i>
</p>
因此,第二次单击时,没有ID为#result
的元素。
我建议(作为一种粗略而快速的解决方案):
在每个请求上,删除您的#result
元素的所有子元素,然后再次用新数据填充。因此,在发出请求之前添加以下行-$('#result').empty();
,并将$('#result').replaceWith(text);
替换为$('#result').append(text);
主要思想是保留放置的位置并添加服务器数据。希望这会有所帮助!