简体   繁体   English

JavaScript中的PHP代码获取变量

[英]PHP code in JavaScript to get variable

When I press on any of the 'region' names in the list (' href ' links), the matching list of 'cities' is showing underneath. 当我按下列表中的任何“区域”名称(“ href ”链接)时,匹配的“城市”列表显示在下方。

<?php while(has_list_regions()) { ?>
  <a href="javascript:show_region('<?php echo list_region_id() ?>');"></a>
<?php } ?>

<script type="text/javascript">
  function show_region(chosen_region_id) 
  {
      ;     
      $(this).slideDown(200);
      ;
        <?PHP $clicked_tag = 'chosen_region_id'; ?>
  }
</script>

Is it possible to include PHP code within a section of JavaScript? 是否可以在JavaScript部分中包含PHP代码? Because I need to get the ID of the selected ' href ' that I clicked. 因为我需要获取单击的所选' href '的ID。 I am trying to include the PHP code in the above JavaScript function but it doesn't work. 我正在尝试在上述JavaScript函数中包含PHP代码,但是它不起作用。

PHP runs on the server, generates the content/HTML and serves it to the client possibly along with JavaScript, Stylesheets etc. There is no concept of running some JS and then some PHP and so on. PHP在服务器上运行,生成内容/ HTML,并可能将其与JavaScript,样式表等一起提供给客户端。不存在先运行JS然后运行PHP等的概念。

You can however use PHP to generate the required JS along with your content. 但是,您可以使用PHP生成所需的JS及其内容。

The way you've written it won't work. 您编写的方式行不通。


For sending the value of clicked_tag to your server, you can do something like (using jQuery for demoing the logic) clicked_tag的值发送到服务器,您可以执行类似的操作(使用jQuery演示逻辑)

function show_region(chosen_region_id) {
    ...
    $.post('yourserver.com/getclickedtag.php', 
        {clicked_tag: chosen_region_id}, 
        function(data) { ... });
    ...
}

在脚本中,变量chosen_region_id已存在于函数中,因此您实际上不需要使用PHP再次声明它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM