【问题标题】:Passing Jquery variable to php within a modal在模态中将 Jquery 变量传递给 php
【发布时间】:2015-07-05 01:17:54
【问题描述】:

我正在打印图片和名称(在网格视图中)。用户将能够单击图片或名称,这将打开一个带有被单击的图片/名称(相同)标题的模式。

<?php
    $i = 0;
    while ($row = mysqli_fetch_assoc($data)) {
        print '<li>';
        print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
        print '<a class="btn btn-default" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
        print '</li>';
    }
?>

单击图像/名称时,如何将图像路径或单击的名称存储到变量并将其发送到 php,以便我可以运行查询并获取更多信息(基于单击)来填充模态?

我正在阅读另一篇文章:How to pass jQuery variables to PHP variable? 但这仅适用于单一情况,我将如何传递使用 while 循环打印出来的变量?

模态框的data-id 标签在这里有用吗?

【问题讨论】:

  • 您的数据是否有任何唯一标识符?像 id。因为其他数据的名称或图像 src 可以相同。
  • 是的,有一个 id...只是我不太确定如何实现对它的搜索...现在我知道如何根据显示的内容进行搜索。

标签: php jquery html twitter-bootstrap


【解决方案1】:

尝试对元素进行 ajax 调用 onClick

<?php
        $i = 0;
        while ($row = mysqli_fetch_assoc($data)) {
            print '<li>';
                print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image.jpg" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
                print '<a class="pass_href btn btn-default" data-toggle="modal" data-href="test/path/to-the-image-2.jpg" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
            print '</li>';
        }
    ?>

现在的 jQuery

$(function(){
    $('.pass_href').click(function(){
      var href = $(this).attr('data-href');
      $.post( "test.php", { href:href } );
    });
});

【讨论】:

  • 啊,所以如果我没看错的话,jqeury 部分会识别被点击的 href,然后将 href 分配给变量 href.. 然后将其发布到页面(在这种情况下test.php),对吧?你会怎么解释这个? jquery代码的第2行和第3行有什么区别? (是不是一个识别点击,另一个设置变量?)
  • 另外,我在 php 标签中收到了这样的变量:$name = $_GET['href'];,但我收到了消息:Undefined index:href。我也试过$_POST,同样的错误
  • 还是会喜欢这个解决方案
  • 我用$_POST['href']; 试过了,结果还是一样
【解决方案2】:

要显示有关模式的详细信息,您需要使用 ajax 发布表单。这里我给你一个解决方案。首先在两个按钮中添加一个 data-id 属性,并在 onclick 事件中调用 function .

print '<li>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><img src="'.$row["image"].'" /></a><br>';
print '<a class="btn btn-default" data-id='.$row['id'].' onclick="show(this);" data-toggle="modal" data-target=".bs-example-modal-lg"><h4>'.$row['name'].'</h4></a>';
print '</li>';

然后在该函数调用上使用 ajax 发布表单。like-

<script>
function show(x){
    var id = $(x).data('id');
      $.ajax({
        type: "POST",
         url: "your/url",
         data: { id: id},
             success: function(data) {
                //parse your json data
                    var obj = $.parseJSON(data);
                    if (obj != null){
                      //append/show your data in your modal body
                    }
              }
          });                              
         } 
</script>

并在您的 php 函数中接收您发布的 id 并从数据库或任何地方查找该 id 的详细信息。然后使用 php json_encode() 函数将您的数据返回为 json 类型。

【讨论】:

  • 感谢您的回答,所以我从来没有使用过json,我不太清楚如何在jquery中//append/show your data in your modal body。有没有更简单的方法呢?就像在另一个答案中一样?另外,我正在尝试,但在这种情况下,我如何获得 php 中的值呢?是不是类似:$name = $_GET['obj']; ? 另外,我有必要返回任何数据吗?查询db后不能在php中显示吗?
  • 是的,类似的。这是表单提交,仅此而已。就像$id = $_POST['id']; 的正常方式一样,您可以接收数据。然后使用json_encode('your data array or whatever you want to return') 返回您的数据。然后使用$.parseJSON(data) 解析您返回的数据。现在显示它们-为了在模态正文中显示您的数据,您应该为每个数据保留空格/标签。就像您想在模态中显示名称一样,然后您可以保留一个具有特定 ID 的 div 并更改其 html像这样的 div-$("#your-div-Id").html(obj["your data"]);
  • 接收变量时出现未定义索引错误。我试过了:$id = $_POST['id'];$id = $_GET['id'];
  • 您能否通过警报检查您的var id 是否具有价值?只需在var id 之后添加alert(id) 之类的警报即可。
  • 是的,是返回值,第一张图片返回1,第二张返回2
【解决方案3】:

基本上,您需要做的是:

  1. 使用php 代码将图片加载到页面上
  2. 同时,加载选择每张图片的按钮/链接
  3. 为每个按钮添加一个data 属性并将每个图像记录的数据库行ID 存储在该数据属性中(这些按钮也都设置为打开相同的模式)
  4. 当用户点击按钮时,从点击的按钮中获取存储的row id
  5. 对另一个传入行 id 的 php 页面进行 ajax 调用
  6. 在另一个php页面上,使用id查找记录并返回所有字段
  7. 回到第一页,当ajax调用返回时,使用返回的数据填充modal的内容

Here is a working example

另请注意:根据您从数据库中获取的其他信息,您可能只在第一页加载时将所有信息存储在按钮的数据属性中,并避免 ajax 调用 all一起。当然,如果您要获取大量数据,例如 pdf 文件之类的,那可能不切实际。

完整代码:imagesfromdb.php(主页):

<?php
    // remove below for production
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    // remove above for production
    
    // change these to your own database details
    $db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    $sql = 'SELECT id, url FROM imagebase ORDER BY id';  
    $stmt = $db->prepare($sql);
    $stmt->execute(); 
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);  
    
    $imgGroups=array();
    // check for errors 
    if($stmt->errorCode() == 0) {
        // no errors
        foreach($rows as $row) {
            $id = $row['id'];
            $url= $row['url'];
            $imgGrp ='<div class="col-sm-4">'.
                      '<div class="row">'.
                        '<div class="col-sm-12 text-center"><img src="'.$url.'" width="100" height="100" alt=""/></div>'.
                        '<div class="col-sm-12 text-center">'. //note the addition of the "data-row-id" attribute below
                          '<button type="button" class="btn btn-primary get-data" data-row-id="'.$id.'" data-toggle="modal" href="#my-modal">Select image</button>'.
                        '</div>'.
                      '</div>'.
                    '</div>';
            array_push($imgGroups,$imgGrp);
        }
    } else {
        // had errors
        $errors = $stmt->errorInfo();
        return $errors[2];
    }
    
?>
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <title>Images From Database Test</title>

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <style>
img {
    display: block;
    margin-left: auto;
    margin-right: auto
}
</style>
    </head>
    <body>
<div class="row  text-center" >
      <h1>Image From DB Test</h1>
    </div>
<div class="row" >
      <div class="col-sm-12" id="image-groups"> <?php echo join('',$imgGroups); ?> </div>
    </div>

<!-- Modal 7 (Ajax Modal)-->
<div class="modal fade" id="my-modal" >
      <div class="modal-dialog">
    <div class="modal-content modal-shadow">
          <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="my-modal-title" >Help</h4>
      </div>
          <div class="modal-body">
        <div class="col-sm-12 text-center"><img src="" class="image" id="my-modal-image" width="100" height="100" alt=""/></div>
        <div class="col-sm-12 text-center description" id="my-modal-description"> </div>
      </div>
          <div class="modal-footer">
        <button type="button" id="" class="btn btn-default  reload" data-dismiss="modal">Close</button>
      </div>
        </div>
  </div>
    </div>

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> 
<!-- Latest compiled and minified JavaScript --> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script> 
<script>
     $(function(){
         // when the user clicks on one of the buttons, get the id from the clicked button 
         // then make an ajax call to another php page 
         $('#image-groups').on('click', '.get-data', function(){
             var id = $(this).data('row-id');
             var sendVars = 'id='+encodeURIComponent(id);
                $.ajax({
                    type: "POST",
                    url: "getimagedetails.php",
                    data: sendVars, 
                    success: function(rtnData) {
                       rtnData = $.parseJSON(rtnData)
                       $('#my-modal-title').html(rtnData.title);
                       $('#my-modal-image').attr('src', rtnData.url);
                       $('#my-modal-description').html(rtnData.description);
             
                        
                    }
                });
         });
         
         
     });
    </script>
</body>
</html>

完整代码:getimagedetails.php(我们进行 ajax 调用的页面)

  <?php
    // remove below for production
    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);
    // remove above for production
    
    // change these to your own database details
    $db = new PDO('mysql:host=sotestdbuser.db.10125908.hostedresource.com;dbname=sotestdbuser;charset=utf8', 'sotestdbuser', 'Sotestuser398!'); 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // later, change ERRMODE_WARNING to ERRMODE_EXCEPTION so users wont see any errors
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    
    

    if(isset($_POST['id'])){
        
        $sql = 'SELECT url, title, description FROM imagebase WHERE id=?  LIMIT 1';  // "?"s here will get replaced with the array elements belowlinkslinks
        $stmt = $db->prepare($sql);
        $stmt->execute(array($_POST['id'])); // these array elements will replace the above "?"s in this same order
        $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        // check for errors 
        if($stmt->errorCode() == 0) {
            // no errors
            $rowdata = 'test';
            foreach($rows as $row) {
                $rowdata = array('url' =>$row['url'], 'title' =>$row['title'], 'description' =>$row['description']);
            }
            echo json_encode($rowdata);
        } else {
            // had errors
            $errors = $stmt->errorInfo();
            echo $errors[2];
        }
    }
?>

【讨论】:

  • 这正是我一直在寻找的,我会实现它并返回。非常感谢。
  • 天哪,它有效!不可能它真的有效!这太疯狂了!非常感谢!!
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2013-02-19
  • 2016-12-21
  • 2017-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-24
相关资源
最近更新 更多