Javascript 是否可以将HTML输入类存储到PHP变量中?
我有一个html表单,一些php和一点javascript。表单有两个输入标记。两个输入标记都有类属性。我想在PHP变量中“存储”类值,这样我可以在单击submit后回显 我曾尝试将javascript与第一个php变量$firstclass集成,但即使作为警报也无法使其正常工作。我真的不想提醒类值,但我认为这将有助于找到解决方案Javascript 是否可以将HTML输入类存储到PHP变量中?,javascript,php,html,Javascript,Php,Html,我有一个html表单,一些php和一点javascript。表单有两个输入标记。两个输入标记都有类属性。我想在PHP变量中“存储”类值,这样我可以在单击submit后回显 我曾尝试将javascript与第一个php变量$firstclass集成,但即使作为警报也无法使其正常工作。我真的不想提醒类值,但我认为这将有助于找到解决方案 <form action="" method="post"> <input type="t
<form action="" 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>
<?php
$firstclass = ""; //hidden_class_1
$secondclass = ""; //hidden_class_2
$firstclass = "<script type=\"application/javascript\">alert(('this.className').attr('class'))</script>";
$secondclass = ""; //ideally hidden_class_2
if(isset($_POST['submit'])){
echo "<h2>First Input Class Value: ".$firstclass."</h2>";
echo "<h2>Second Input Class Value: ".$secondclass."</h2>";
}
我预计产出如下:
第一个输入类值:隐藏类1
第二个输入类值:hidden_Class_2最简单的方法是使用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>
在PHP内部,可以使用$\u POST或$\u 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_编码和json_解码函数。例如,您的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);
}
使用ajax-不要混合使用PHP和JS有趣,你能提供一个例子吗?只有在你同意使用jQuery的情况下-我不知道所需函数的vanilla JS等价物。我同意使用jQuery,如果你能提供一个工作示例,我将不胜感激
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);
}