1 回答

TA貢獻(xiàn)1895條經(jīng)驗(yàn) 獲得超3個(gè)贊
“最簡(jiǎn)單”的方法是使用 AJAX/XHR 并將類發(fā)送到 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) 來(lái)獲取已發(fā)送的值:
$input1_value = $_POST['input1Value'];
$input2_value = $_POST['input2Value'];
$input1_class = $_POST['input1Class'];
$input2_class = $_POST['input2Class'];
# do what you want with the variables
請(qǐng)注意,您必須在onSuccess函數(shù)內(nèi)部處理服務(wù)器的響應(yīng)。通常,人們使用 JSON 對(duì)來(lái)自服務(wù)器的響應(yīng)進(jìn)行建模。您可以使用 PHP 的內(nèi)置函數(shù)json_encode和json_decode函數(shù)。例如,您的 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函數(shù)內(nèi)部,您將例如:
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 關(guān)注
- 134 瀏覽
添加回答
舉報(bào)