Get PHP variable to javascript
I cant seem to find the answer for this one. I need to grab a PHP variable and insert it into javascript.
Here is an example of what I have in the body of a PHP page:
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php Print($info); ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<?php
$info="some info";
?>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
So the problem is that the alert pops up but doesn't echo the $info string. Obviously i'm missing the right way to grab a PHP variable. Please help.
If the php variable is visible inside the inner HTML, you could do something like this to grab the variable:
HTML:
<span class="variable-content"><?php echo $variable; ?></span>
jQuery:
var php_variable = $(".variable-content").text();
alert(php_variable);
Change:
alert(info);
to:
alert('<?php echo "some info"; ?>');
It looks to me like you are declaring the variable after you use it. So there is nothing in $info.
try:
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo $info; ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
链接地址: http://www.djcxy.com/p/59354.html
上一篇: 将域URL添加到href和src相对路径
下一篇: 获取PHP变量为JavaScript