首先让我说我是使用 AJAX 的新手,昨天才开始。
这是我的代码:
<?php
if (isset($_POST['number1'],$_POST['operation'],$_POST['number2'])) {
$number1 = trim(strip_tags($_POST['number1']));
$number2 = trim(strip_tags($_POST['number2']));
$operation = $_POST['operation'];
if ($operation == "plus") {
$answer = $number1 + $number2;
$operation = "+";
}
if ($operation == "minus") {
$answer = $number1 - $number2;
$operation = "–";
}
if ($operation == "multiply") {
$answer = $number1 * $number2;
$operation = "×";
}
if ($operation == "divide") {
$answer = $number1 / $number2;
$operation = "÷";
}
$output = '<br /><center><div id="success"><span style="color: orange; font-size: 20px;">'.number_format($number1).'</span> <span style="color: blue; font-size: 24px; font-weight:bold;">'.$operation.'</span> <span style="color: orange; font-size: 20px;">'.number_format($number2).'</span> <span style="color: blue; font-size: 24px; font-weight:bold;">=</span> <span style="color: purple; font-size: 20px;">'.number_format($answer).'</span></div>
';
echo $output;
die();
}
?>
<form method="POST" id='calculatorForm'>
<input type="number" name="number1" id="url" placeholder="Enter your first number" autofocus required />
<br />
<select name="operation" id="url" style="width:100%;">
<option value="operation">Select A Operation:</option>
<option value="plus">Plus</option>
<option value="minus">Minus</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<br />
<input type="number" name="number2" id="url" placeholder="Enter your second number" required />
<input type="submit" class="enter" id="submit" name="submit" value="Calculate!">
<br />
<span style="font-size:40px;color: purple;font-wight: bold;">Result: <span id='result'>0</span></span>
</form>
<script>
$('#calculatorForm').submit(function(){
var num1 = $('input[name="number1"]').val();
var oper = $('select[name="operation"]').val();
var num2 = $('input[name="number2"]').val();
$.ajax({
type: "post",
data: {number1: num1, operation: oper, number2: num2},
success: function(data){
$('#result').html(data);
}
});
return false;
});
</script>
当我尝试使用表单提交在我的页面上运行此代码时,它会在我的表单下再次给我整个页面,并且没有计算我输入的内容。