javascript - 无法以html形式写入AJAX输出变量

标签 javascript html ajax

我需要在跨度标签(“estimation2”)内打印计算结果(目前,只是两个输入框“SHm2”和“STm2”的简单求和)。我正在使用 AJAX 调用来执行该任务。它似乎工作完美,直到警报显示正确的结果,但由于某些原因,我无法将该结果写入我的 html 表单。我环顾四周并尝试了几种方法,但没有一个起作用。例如,我尝试使用 write 方法,但它不起作用或类似 $("#estimation2").html(estimation);document.getElementById("estimation2").innerHTML = 估计; 我设法编写它的唯一方法是使用 window.onload,但这会在页面加载时生成计算,而我不希望这样。我只希望在单击按钮时触发 AJAX 代码。 另外,仅供引用,计算是在我的 django View 中进行的,尽管我认为它与此处无关,因为它看起来工作正常。我真的迷路了,你能帮忙吗?

这是我的 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>

最佳答案

所以你想要做的是在 HTML 文档加载后运行 JS,正如评论部分中提到的,你需要将 type="button" 添加到 esimation 按钮

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" 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;
      }
    });
  }
});

关于javascript - 无法以html形式写入AJAX输出变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60681399/

相关文章:

javascript - ajax:从json数组中提取json对象

javascript - Ajax如何做异步请求和响应同步结果

javascript - 检查<select>中选定的项目-Roll?

php - 使用 HTML5 pushstate 请求 ajax 时 undefined index 通知

html - 将文本放在 div 的右侧

javascript - HTML5 数字输入 - 显示为百分比而不是小数

javascript - 使用 bootstrap3 modal、jquery 和 Rails 4 为我当前的模型创建父对象

javascript - Angular 2 在不应该更新 View 的时候更新了 View?

javascript - Angular : defining a module or not

javascript - 从列表/播放列表和循环播放随机 YouTube 视频