在加载脚本中包含PHP变量

时间:2017-06-02 12:48:08

标签: javascript php jquery

我提前为我的(可能)愚蠢的问题道歉,但我对Javascript / JQuery的了解几乎为0

我在index.html中有以下脚本:

的index.html

<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { 
   $("#MyDIV")
   .load("buttons.php") 
  });
</script>
<div id="MyDIV"></div>

正如您所看到的,想法是在 index.html 的div标记中加载 buttons.php - 这很好用 -

buttons.php

<div id="buttom">
    <div id="botton5"><a href="#"><img src="5.png" id="5"/></a></div> 
</div>
<script> 
$('#botton5').click(function(event){ 
   $("#bottons").load('somepage.php?answer=5');  //here!

}); 
</script>

多数民众赞成正常,我从index.html的MyDIV中的somepage.php收到信息

但是当我在行

中的URL中包含php时不起作用
$("#bottons").load('somepage.php?answer=5&title=<?php echo $title;?>&date=<?php echo $date;?>');   //here!

在加载中包含一个PHP,div不会在index.html中加载,你能否支持我如何在加载URL中添加php?

提前感谢您的支持

1 个答案:

答案 0 :(得分:0)

@Luis Gerardo Runge 在JavaScript中,您无法使用PHP,但从逻辑上讲,您可以在隐藏字段中使用您的价值并在javascript中使用。我添加了一些示例代码,我可以帮助您

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head> 
<div id="buttom">
    <div id="botton5"><a href="#"><img src="5.png" id="5"/></a></div> 
</div>
<div id="bottons">

</div>
<?php 
$title = 'your title';
$date = 'yourdate';
?>
<input type="hidden" id="title" name="title" value="<?php echo urlencode($title); ?>">
<input type="hidden" id="date" name="date" value="<?php echo urlencode($date); ?>">

<script> 
$('#botton5').click(function(event){ 
alert('call');
   $("#bottons").load('json.php?answer=5&title='+$('#title').val()+'&date='+$('#date').val()+'');  //here!

}); 
</script>

仅供参考:您需要通过URL

使用urlencode和urldecode传递参数