我需要将jquery变量的值复制到PHP变量中。
我的代码:
<script>
$(document).ready(function() {
var gtext = "Sample text";
console.log(gtext); //I get the gtext printed in console
<?php $variablephp = "<script>document.write(gtext)</script>" ?>
<?php echo $variablephp; ?> // I cannot get printed this php variable
<?php echo "hi"; ?> //This echo statement not get printed
});
</script>
有人可以帮忙吗?
我的问题在于我想在PHP变量中存储jquery值。不是PHP变量到jquery元素。
答案 0 :(得分:1)
这将是一个php to jquery方法
<script type="text/javascript">
$(document).ready(function(){
var example = '<?php echo $phpVariable; ?>';
});
</script>
答案 1 :(得分:0)
你可以像这样使用php:
<script>
$(document).ready(function (e) {
<?php if (isset($variable) && $variable !=''){ ?>
var abc = 'this';
<?php }else{ ?>
var abc = 'that';
});
</script>
答案 2 :(得分:0)
好。那么为什么我想将jquery值存储到PHP变量中,我希望将jquery中的值作为PHP中的会话变量。
因为我希望这些jquery值对每个用户都是特定的。
jquery本身是否有任何其他选项,在PHP中表现这个jquery值就像一个会话变量?
对不起,如果这是无关紧要的,因为我对这一切都不熟悉。
答案 3 :(得分:0)
这将是php方法的jquery
在index.php里面
<button id="button1">Press Me</button>
<script type="text/javascript">
$( "#button1" ).click(function() {
$.ajax({
method: "POST",
url: "server.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
});
});
</script>
<?php
//This will display the session data
if(!empty($_SESSION)) {
print '<pre>';
print_r($_SESSION);
print '</pre>';
}
?>
在server.php中
<?php
session_start();
function cleanInput($string)
{
return preg_replace("/[^A-Za-z0-9 ]/", '', $string);
}
if(!empty($_POST['name'])) {
$_SESSION['name'] = cleanInput($_POST['name']);
}
if(!empty($_POST['location'])) {
$_SESSION['location'] = cleanInput($_POST['location']);
}
然后在用户点击按钮后,如果他们刷新页面,php $ _SESSION将包含新数据