【问题标题】:AJAX success not render properly since second request自第二次请求以来,AJAX 成功无法正确呈现
【发布时间】: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


【解决方案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>

所以第二次点击没有#result id的元素。

我建议(作为一个粗略而快速的解决方案):

在每次请求时,删除您的 #result 元素的所有子元素并用新数据再次填充它。所以在发出请求之前添加这一行 - $('#result').empty(); 并将 $('#result').replaceWith(text); 替换为 $('#result').append(text);

主要思想是保留您放置的位置并添加您的服务器数据。希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 1970-01-01
    相关资源
    最近更新 更多