我需要在跨度标签(“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/