我构建了一个小应用程序来验证从服务器端的表单提交的数据,然后根据用户输入显示结果。这一切都很完美,但我想改善用户体验,并在不修改现有PHP代码的情况下整合AJAX(至少不会太多)。
该应用程序的基本逻辑是,如果服务器请求是GET,则显示表单(请参阅index-get.php),如果是POST(即表单已提交),则验证表单。如果有错误,它会重新显示带有错误消息的表单,否则它会处理表单(index-post.php)。
我正在使用jQuery的ajax()方法(请参阅带有标题'grade-calulator.js'的块来执行此操作但是它不验证输入并且只是从'index-post.php'返回此行:
echo '<p id="response">You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.</p><br>';
的index.php
<div class="container">
<div class="starter-template col-sm-6 col-sm-offset-3">
<?php
//Set up empty defaults when nothing is chosen
$defaults = array(
'currentGrade' => '',
'targetGrade'=> '',
'finalWorth' => '');
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$errors = array();
include __DIR__ . '/index-get.php';
} else {
$errors = validate_form();
if (count($errors)) {
//if there were errors, redisplay form with the errors, preserving defaults. Otherwise process the form.
if (isset($_POST['currentGrade'])) { $defaults['currentGrade'] = $_POST['currentGrade']; }
if (isset($_POST['targetGrade'])) { $defaults['targetGrade'] = $_POST['targetGrade']; }
if (isset($_POST['finalWorth'])) { $defaults['finalWorth'] = $_POST['finalWorth']; }
include __DIR__ . '/index-get.php';
} else {
include __DIR__ . '/index-post.php';
}
}
function validate_form() {
//start out with no errors
$errors = array();
// currentGrade must be filled out and be a number.
if (! filter_has_var(INPUT_POST, 'currentGrade') === false && filter_input(INPUT_POST, 'currentGrade', FILTER_VALIDATE_INT) === false) {
$errors['currentGrade'] = "You need to enter a number for current grade";
}
if ($_POST['currentGrade'] < 0) {
$errors['currentGrade'] = "Current grade must be greater than zero";
}
// targetGrade must be filled out and be a number.
if (! filter_has_var(INPUT_POST, 'targetGrade') === false && filter_input(INPUT_POST, 'targetGrade', FILTER_VALIDATE_INT) === false) {
$errors['targetGrade'] = "You need to enter a number for target grade";
}
// finalWorth must be filled out and be a number.
if (! filter_has_var(INPUT_POST, 'finalWorth') === false && filter_input(INPUT_POST, 'finalWorth', FILTER_VALIDATE_INT) === false) {
$errors['finalWorth'] = "Your final exam worth needs to be a number.";
}
return $errors;
}
?>
</div>
</div><!-- /.container -->
索引get.php
<form action="<?php echo htmlentities($_SERVER['SCRIPT_NAME']) ?>" method="post" id="gradeForm">
<div class="form-group <?php if (isset($errors['currentGrade'])) { echo 'has-error'; } ?>">
<label for="currentGrade">What is your current total grade?</label>
<input type="text" class="form-control" name="currentGrade" value="<?php echo htmlentities($defaults['currentGrade'])?>">
<?php if (isset($errors['currentGrade'])) { ?>
<span class="help-block"><?php echo htmlentities($errors['currentGrade'])?></span>
<?php } ?>
</div>
<div class="form-group <?php if (isset($errors['targetGrade'])) { echo 'has-error'; } ?>">
<label for="targetGrade">What is your target grade?</label>
<input type="text" class="form-control" name="targetGrade" value="<?php echo htmlentities($defaults['targetGrade'])?>">
<?php if (isset($errors['targetGrade'])) { ?>
<span class="help-block"><?php echo htmlentities($errors['targetGrade'])?></span>
<?php } ?>
</div>
<div class="form-group <?php if (isset($errors['finalWorth'])) { echo 'has-error'; } ?>">
<label for="finalWorth">What is your final exam worth?</label>
<input type="text" class="form-control" name="finalWorth" value="<?php echo htmlentities($defaults['finalWorth'])?>">
<?php if (isset($errors['finalWorth'])) { ?>
<span class="help-block"><?php echo htmlentities($errors['finalWorth'])?></span>
<?php } ?>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
索引post.php中
<?php
$currentGrade = $_POST['currentGrade'];
$targetGrade = $_POST['targetGrade'];
$finalWorth = $_POST['finalWorth'];
echo $currentGrade . " " . $targetGrade . " " . $finalWorth;
if (isset($currentGrade, $targetGrade, $finalWorth)) {
$possibleGradeSoFar = (100 - $finalWorth) / 100;
$finalWorth = $finalWorth / 100;
$b = $currentGrade * $possibleGradeSoFar;
$c = $targetGrade - $b;
$neededMark = $c / $finalWorth;
$neededMark = round($neededMark);
if ($neededMark >= 50 && $neededMark <= 100) {
echo '<h1>Better start studying...</h1>';
echo '<img class="img-responsive" src="img/Mike.gif" alt="Mike">';
} elseif ($neededMark > 100) {
echo '<h1>Just give up now.</h1>';
echo '<img class="img-responsive" src="img/Gustavo-fring.gif" alt="Gustavo Fring">';
} elseif ($neededMark < 50) {
echo '<h1>Time to party!</h1>';
echo '<img class="img-responsive" src="img/Yeah-science.gif" alt="Yeah Science!">';
}
}
echo '<p id="response">You need to get ' . $neededMark . ' to get a final mark of ' . $targetGrade . '.</p><br>';
级-calculator.js
//ajax for the form
$('form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr("action");
var formData = $(this).serialize();
console.log(formData);
$.ajax(url, {
data: formData,
type: "POST",
success: function(response) {
$('#gradeForm').load('index-post.php');
}
});
});
答案 0 :(得分:1)
我不会尝试重新编写您所拥有的内容,但我会告诉您如何做您想做的事情......
index.php //这是您的表单和其他HTML将存在的地方:)
<div id="msgs"></div>
<!-- we don't need a value for action as the ajax function will define where the form data is being posted -->
<form id="my-form" action="" method="post">
<input type="text" name="hello_ajax" />
<input type="submit" value="Save" />
</form>
<!-- make sure jQuery is included in the header or somewhere before this!! -->
<script type="text/javascript">
jQuery(document).ready(function($){
$('#my-form').on('submit',function(e){
e.preventDefault(); // this will prevent the form from refreshing the page (POSTing to itself)
//we'll use the $.post method...
var form = $(this);
var postData = form.serialize();
$.post('http://website.com/handler.php',postData,function(resp){
if(resp.success){
//everything went as expected! remove the form and display the message..
form.remove();
$('#msgs').html(resp.msg);
}else{
//we encountered an error...leave the form, display the message
//here you could add an error class to the message box etc..
$('#msgs').html(resp.msg);
}
},'json'); //we expect a json response from handler.php
});
});
</script>
handler.php //这是将处理ajax提交的人..
<?php
//make sure to secure this better, a common way is to make sure it was submitted using an http request...
if(isset($_POST['hello_ajax'])){
if($_POST['hello_ajax'] == ''){
//this is required so we'll return an error..in JSON..
$resp['success'] = false;
$resp['msg'] = 'Hello Ajax is required!';
//we output, NOT return the response..
exit(json_encode($resp));
}else{
//looks good save it or whatever...
/** Saving/Calculating code here... **/
//output a positive response
$resp['success'] = true;
$resp['msg'] = 'Hello Ajax was saved!!';
exit(json_encode($resp));
//that's it...
}
}
?>
这应该让你指向正确的方向!!干杯!