【问题标题】:Pass id from php to JS file将 id 从 php 传递到 JS 文件
【发布时间】:2012-09-18 09:29:22
【问题描述】:

我很清楚这个问题被问了很多次,但我的问题有些不同,我没有找到解决方案。

现在问题来了。

我有一张图片,所以每当我点击图片时,弹出窗口就会打开并显示数据。现在我想让它动态化,并希望数据应该根据 id 来。

这是我的图片代码:

<div id='contact-form'>

        <a href='#' class='contact'><img src="<?php echo base_url();?>/assets/images/pre.jpg" style="height:18px; width:18px"></a>
      </div>
        <!-- preload the images -->
        <div style='display:none'>
            <img src='<?php echo base_url();?>assets/images/img/contact/loading.gif' alt='' />
        </div>  


And on its click the ajax is called from js file here is the code of that js file:
//here the provider is controller and show_coupon_pre is a function which call the view having the data.
$.get("provider/show_coupon_pre", function(data){
                    // create a modal dialog with the data
                    $(data).modal({
                        closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
                        position: ["15%",],
                        overlayId: 'contact-overlay',
                        containerId: 'contact-container',
                        onOpen: contact.open,
                        onShow: contact.show,
                        onClose: contact.close
                    });
                });

我有一个没有记录的表,每个记录都有这种类型的图像。用户可以单击并在弹出窗口中获取预览。 但我想根据 id=1 的行在弹出窗口中显示数据,它应该显示 id==1 的数据,依此类推。现在你们能帮我吗?如何将此ID传递给我可以获取所需数据的js文件。

我在 codeignitor 工作。

【问题讨论】:

标签: php javascript ajax codeigniter


【解决方案1】:

最简单的解决方案

<table>
<tr>
 <td><img class="banner" src="/image1.png" post_id="1"></td>
 <td>some other data 1</td>
</tr>
<tr>
 <td>
 <td><img class="banner" src="/image1.png" post_id="2"></td>
 <td>some other data 2</td>
</tr>
</table>

Javascript:

$('.banner').click(function() { 
  post_id = $(this).attr("post_id");

  // send your ajax with post_id
} );

【讨论】:

  • 那不是有效的 html。 stackoverflow.com/questions/432174/…
  • 我只是给你一个想法,如何解决这个问题。编写代码来解决你的问题是不可能的,因为我不知道html页面是如何生成的以及所有代码是如何工作的。
  • @Maxim 但我如何将此变量传递给 ajax 调用 url $.get("provider/show_coupon_pre", function(data){
  • 我认为它看起来像这样:$.get('provider/show_coupon_pre?coupon_id'+post_id);
  • 我将逐步解释逻辑: 1. 生成带有图像属性的 html 表(参见我放在这个响应中的这个 html 的示例) 2. 为这样的图像添加 onclick(我想你已经做了this) 3. 在“onclick”事件中,从调用者那里获取你的属性值 4. 初始化 ajax:$.get('provider/show_coupon_pre?coupon_id'+post_id, function(data) { YOUR CODE HERE. Open Modal To user }) ;
【解决方案2】:

如果你在输出图片时有 php 中的 ID,我会这样做:

<script>
var randomId = <?php echo '"' . $phpId . '"'; ?>
</script>

【讨论】:

  • 现在如何将这个 java 脚本变量传递给调用 ajax 的 js 文件。
  • 将我的示例放在您的 JS 文件的包含上方。您应该可以访问它。例如 alert(randomId) 它应该在范围内。
猜你喜欢
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多