我需要在span标记("estimation2")中打印计算结果(就目前而言,只是两个输入框"SHm2“和”STm2“的简单和)。我正在使用AJAX调用来执行该任务。在显示正确结果的警报之前,它似乎工作得很好,但出于某些原因,我无法在html表单中写入该结果。我四处张望,尝试了好几件事,但都没有用。例如,我尝试过使用写方法,但是它不起作用,或者像$("#estimation2").html(estimation);或document.getElementById("estimation2").innerHTML = estimation;之类的东西,我设法编写它的唯一方法是使用window.onload,但是这会在页面加载时生成计算,我不想这样做。我只希望在单击按钮时触发AJAX代码。此外,只是为了获得信息,计算是在我的django视图中进行的,尽管我认为它在这里不相关,因为它看起来工作正常。我真的迷路了,你能帮忙吗?
下面是我的html代码和AJAX脚本:
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
<script type="text/javascript">
    function calculate () {
      var SHm2 = $('#SHm2').val();
      var STm2 = $('#STm2').val();
      $.ajax({
              url: '/myApp/templates/homepage/',
              type: 'POST',
              data: {
                'SHm2':SHm2,
                'STm2':STm2,
                estimation: 'estimation',
              },
              success: function(estimation) {
              alert(estimation);
              document.getElementById("estimation2").innerHTML = estimation;
              }
      }); 
    }
</script>发布于 2020-03-14 10:18:00
因此,您要做的是在加载了HTML文档之后运行JS,正如注释部分所提到的,您需要将type="button"添加到estimation按钮中。
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" type="button" onclick="calculate()" >Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>JS
 $(document).ready(function() {
   function calculate() {
    var SHm2 = $("#SHm2").val();
    var STm2 = $("#STm2").val();
    $.ajax({
      url: "/myApp/templates/homepage/",
      type: "POST",
      data: {
        SHm2: SHm2,
        STm2: STm2,
        estimation: "estimation"
      },
      success: function(estimation) {
        console.log(estimation);
        document.getElementById("estimation2").innerHTML = estimation;
      }
    });
  }
});https://stackoverflow.com/questions/60681399
复制相似问题