1 回答
TA贡献1895条经验 获得超3个赞
“最简单”的方法是使用 AJAX/XHR 并将类发送到 PHP 脚本。
<form id="ajaxform" action="path/to/script.php" method="post">
<input type="text" name="input1" class="hidden_class_1">
<input type="text" name="input2" class="hidden_class_2">
<input type="submit" name="submit">
</form>
例如,使用 jQuery:
const $form = $('#ajaxform');
function onSuccess (response) {
console.log('Successfully submitted the form');
console.log('Server responded with', response);
}
function onFailure (jqXhr, status) {
console.log('Ooops, something went wrong!');
console.log('Server sent status code', status);
}
$form.on('submit', event => {
event.preventDefault(); // suppress the reload
const $input1 = $form.find('[name=input1]');
const $input2 = $form.find('[name=input2]');
$.ajax({
method: $form.prop('method').toUpperCase(),
url: $form.prop('action'),
data: {
input1Value: $input1.val(),
input2Value: $input2.val(),
input1Class: $input1.prop('className'),
input2Class: $input2.prop('className')
}
}).
done(onSuccess).
fail(onFailure);
});
在您的 PHP 中,您将使用$_POST(或$_REQUEST) 来获取已发送的值:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want with the variables
请注意,您必须在onSuccess函数内部处理服务器的响应。通常,人们使用 JSON 对来自服务器的响应进行建模。您可以使用 PHP 的内置函数json_encode和json_decode函数。例如,您的 PHP 脚本可以回答:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want to do with the variables, then
$response = array(
'ok' => true,
'message' => 'PHP says "Thanks" for the information'
);
header('Content-Type: application/json');
echo json_encode($response);
die;
在onSuccess函数内部,您将例如:
function onSuccess (response) {
if (response.ok) {
console.log('Submitted, and all values where OK');
console.log(response.message);
return; // opt-out early, no need for "else" keyword
}
console.log('Submitted, but something went wrong');
console.log(response.message);
}
- 1 回答
- 0 关注
- 119 浏览
添加回答
举报