[英]How can I use a variable from javascript in php?
I'm having a brain freeze at the moment.. I have a variable here in this bit of JavaScript code... 目前,我的大脑停滞不前..在这段JavaScript代码中,我这里有一个变量...
<script type="text/javascript">
$('#menuNameEdit').val(reservationId);
</script>
I have managed to use #menuNameEdit
in form input as below but I don't know how to use it as a normal variable in PHP. 我设法在下面的表单输入中使用
#menuNameEdit
,但是我不知道如何在PHP中将其用作普通变量。 For example if I want to compare it's value against another variable. 例如,如果我想将其值与另一个变量进行比较。 Mind Block!
心灵障碍!
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>
You can't. 你不能 It's just not possible.
只是不可能。 If JS starts with its work, PHP is already done.
如果JS开始工作,则PHP已经完成。
The only way to do that - though its extremely vulnerable - is via AJAX: 做到这一点的唯一方法(尽管它非常脆弱)是通过AJAX:
$.ajax({
type: "POST",
url: "your_php_script.php",
data: {var: your_variable},
success: function() {
console.log("ajax successful!");
}
});
Without jQuery: 没有jQuery:
var request = new XMLHttpRequest();
request.open('POST', 'your_php_script.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.send(your_variable);
This needs to be in your_php_script.php: 这需要在your_php_script.php中:
$jsVariable = $_POST['var'];
This is extremely vulnerable though - always sanitize input via filter_var()
or htmlspecialchars()
which could be modified by the user! 不过,这非常容易受到攻击-始终通过
filter_var()
或htmlspecialchars()
filter_var()
输入,用户可以对其进行修改!
If your form gets submitted you can access the below code: 如果提交表单,则可以访问以下代码:
PHP 的PHP
if(isset($_POST['reservationId'])){
echo $_POST['reservationId'];
}
HTML 的HTML
<form method="" action="" id="form-id">
<input id="menuNameEdit" name="reservationId" type="text" class="form-control" disabled>
<input name="submit" type="submit" class="form-control">
</form>
Jquery jQuery的
var menuNameEdit = $('#menuNameEdit').val();
$.ajax({
type: "POST",
url: "index.php",
data: {menuNameEdit : menuNameEdit },
success: function() {
console.log("Success!");
}
});
index.php index.php
echo $_POST['menuNameEdit'];
<?php
if (isset($_POST['submit'])) {
$reservationId = $_POST['reservationId'];
$reservationId2= $_POST['reservationId2'];
//comparison
}
?>
<form class='addcategory' method="post" enctype="application/x-www-form-urlencoded">
<input id="menuNameEdit" name="reservationId" type="text"
class="form-control" disabled>
<input id="another" name="reservationId2" type="text"
class="form-control" >
<input name="submit" type="submit" value="submit">
</form>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.