gpt4 book ai didi

javascript - 在不重新加载页面的情况下提交表单数据

转载 作者:可可西里 更新时间:2023-11-01 13:50:59 25 4
gpt4 key购买 nike

我正在尝试提交表单而不使用 jQuery 重新加载页面本身,但是数据没有显示并且表单正在重新加载,这是不需要的。

jQuery 代码:

function submitFormData() {
var firstval = $("#first").val();
var second = $("#second").val();
//var operator = $("#myselect option:selected" ).text();
$.post("index.php",{first:first,second:second},
function(data){
$('#results').html(data);
$('#formcal')[0].reset();
});
}

这是同一页上的 HTML 代码 (INDEX.PHP):

<form action="" id="formcal" method="post">

<input type="number" id="first" name="first" placeholder="number"/>
<select name="operator" id="operator">
<option value="add">+</option>
<option value = "subtract">-</option>
<option value = "multiply">*</option>
<option value = "division">/</option>


</select>
<input type="number" id="second" name="second" placeholder="number 2"/>
<input type="button" id="submitFormData" onclick="SubmitFormData();" value="Calculate"/>
</form>

<br>
<?php //if(!empty($_POST['first']) && !empty($_POST['second'])){
$number = $_POST['first'];
$number2 = $_POST['second'];

echo "Answer: ";
if($_POST['operator'] == 'add'){
$complete = $number + $number2;
echo " $number + $number2 = $complete";
}
if($_POST['operator'] == 'subtract'){
$complete = $number - $number2;
echo "$number - $number2 = $complete";
}
if($_POST['operator'] == 'multiply'){
$complete = $number * $number2;
echo "$number X $number2 = $complete";
}
if($_POST['operator'] == 'division'){
$complete = $number / $number2;
echo "$number / $number2 = $complete";
}
//}
?>
</div>

<div id="results">
</div>

最佳答案

阻止表单提交的默认操作。

function submitFormData(event) {
// prevent the default action
event.preventDefault();

// Other pieces of code

关于javascript - 在不重新加载页面的情况下提交表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34404512/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com