无法以html格式编写AJAX输出变量

问题描述 投票:0回答:1

我需要在span标签(“ estimation2”)中打印计算结果(目前,仅是两个输入框“ SHm2”和“ STm2”的简单总和)。我正在使用AJAX调用来执行该任务。在显示正确结果的警报之前,它似乎运行良好,但是由于某些原因,我无法以html形式编写该结果。我一直在环顾四周,尝试了几种方法,但没有一种起作用。例如,我尝试使用write方法,但是它不起作用或诸如$("#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>
javascript html ajax
1个回答
1
投票

所以您想做的是在HTML文档加载后运行JS,并且如注释部分所述,您需要将type="button"添加到estimation按钮

HTML

<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">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;
      }
    });
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.