我使用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
,但是它们都不起作用。为什么只有第一个请求后才出错?我怎样才能解决这个问题?谢谢
最佳答案
其不变的原因是您要用接收到的数据替换块#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>
因此,第二次单击时,没有具有
#result
id的元素。我建议(作为一种粗略而快速的解决方案):
在每个请求上,删除您的
#result
元素的所有子元素,然后再次填充新数据。因此,在发出请求之前添加此行-$('#result').empty();
并将$('#result').replaceWith(text);
替换为$('#result').append(text);
主要思想是保留您放置的位置并添加服务器数据。希望这可以帮助!