首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >无法以html形式写入AJAX输出变量

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

Stack Overflow用户
提问于 2020-03-14 09:35:53
回答 1查看 46关注 0票数 0

我需要在span标记("estimation2")中打印计算结果(就目前而言,只是两个输入框"SHm2“和”STm2“的简单和)。我正在使用AJAX调用来执行该任务。在显示正确结果的警报之前,它似乎工作得很好,但出于某些原因,我无法在html表单中写入该结果。我四处张望,尝试了好几件事,但都没有用。例如,我尝试过使用写方法,但是它不起作用,或者像$("#estimation2").html(estimation);document.getElementById("estimation2").innerHTML = estimation;之类的东西,我设法编写它的唯一方法是使用window.onload,但是这会在页面加载时生成计算,我不想这样做。我只希望在单击按钮时触发AJAX代码。此外,只是为了获得信息,计算是在我的django视图中进行的,尽管我认为它在这里不相关,因为它看起来工作正常。我真的迷路了,你能帮忙吗?

下面是我的html代码和AJAX脚本:

代码语言:javascript
运行
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-14 10:18:00

因此,您要做的是在加载了HTML文档之后运行JS,正如注释部分所提到的,您需要将type="button"添加到estimation按钮中。

代码语言:javascript
运行
复制
<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

代码语言:javascript
运行
复制
 $(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;
      }
    });
  }
});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60681399

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档