【问题标题】:How to make a html button target a specific array index in php?如何使 html 按钮以 php 中的特定数组索引为目标?
【发布时间】:2019-10-21 08:54:21
【问题描述】:

我正在编写如下所示的 html/php 代码。在其中单击 html 代码中的按钮时,它会进入 php 中 Line#B 处的 foreach 块

<?php 
     $mp4_files = array_values($mp4_files); 
     print_r($mp4_files);  // Line #A
     if($_SERVER['REQUEST_METHOD'] == "POST")
    {       
     foreach ($mp4_files as $f)  // Line#B
     { 
            // conversion of mp4 into mp3 is happening, not pasting the full code. 
     }
    }
?> 

<form action="" method="POST">
 <table>
       <tr>
          <th>MP4 Name</th>
          <th>Action</th>
       </tr>
      <?php
        $mp4_files = array_values($mp4_files);
        foreach ($programs as $key => $program)  { 
       $file = $mp4_files[$key];     
       print_r($file);   // Line#B
       ?> 
       <tr>
          <td><?php echo basename($file); ?></td>
          <td><button type="submit" name="go-button" value="Go">Go</button</td>
       </tr>
   <?php } ?>
</table>
</form>

以上html/php代码显示如下内容:

在上面的屏幕截图中,我们列出了 mp4 文件及其各自的按钮。

Line#A 从上面的 html/php 代码中打印出以下数组

Array ( [0] => 36031P.mp4 [1] => hello.mp4 ) 

还有线#B:

36031P.mp4 hello.mp4

此时,点击任何表格行中的 Go 按钮,开始将所有 mp4 文件转换为 mp3(这不是我的要求)

问题陈述:

我想知道我应该在上面的 html/php 代码中进行哪些更改,以便如果我从屏幕截图中的 第一行 中单击 Go 按钮,转换第一行 mp4 文件转换为 mp3 应该开始发生,反之亦然

【问题讨论】:

    标签: php arrays ajax post foreach


    【解决方案1】:

    您可以使用数据标签来实现这一点(代码只是示例演示点):

    PHP/HTML

    <?php foreach ($files as $key => $file) : ?>
        <tr>
            <td>
                <span class="file-name" data-id="<?php echo $key; ?>">
                    <?php echo basename($file); ?>
                </span>
            </td>
            <td>
                <button type="submit"
                        class="go-btn"
                        name="go-button"
                        value="Go"
                        data-id="<?php echo $key; ?>"  >
                    Go
                </button
            </td>
        </tr>
    <?php endforeach; ?>
    

    JavaScript (jQuery)

    jQuery(document).ready(function($)
    {
        $('.go-btn').click(function(e)
        {
            //pass in e(vent) to prevent the default behaviour of type="submit"
            e.preventDefault();
    
            let target = $(this).attr('data-id'),
                spanEl = $('.file-name[data-id='+ target +']');
            //do whatever with the spanEl - e.g. .text() to get value
    
            //send the file / ID - depending on how you're retrieving these files
            $.ajax({
                data: {key: 'value'}, //change to what you want
                type: 'post',
                url: '/path/to/script.php',
                success: function(res)
                {
                    alert(res)
                },
                error: function(res)
                {
                    //log the response for debugging
                    console.log(res);
    
                    //tell the user it failed
                    alert('The dark elves have been here.. they broke it!')
                }
            })
        })
    });
    

    脚本.php

    <?php
        # worth nothing that if you're posting a file (with intention of using $_FILES)
        # that you need to change your ajax, add `processData: false, contentType: false, cache: false`
        # and add `enctype="multimedia/form-data"` as an attribute to your form
        $value = $_POST['key']; # key: = index name
    
        # run conversion on the file
        # here we can add a success/error msg
        echo ($success ? 'It converted!' : 'Conversion failed');
    

    到此结束时,您应该有一个类似于(或者至少我会这样做)的文件结构:

    Project_Root
    ----app
    --------convert.php
    ----index.php
    ----pub
    --------js
    ------------main.js
    

    【讨论】:

      【解决方案2】:

      执行此操作的一种肮脏方法是为每个按钮添加一个名称属性,其中包含您希望该按钮附加到的文件的相应文件名。发布时,您将收到一个数组键,其中包含应转换的文件的文件名。你只需要遍历你的 MP4 数组来匹配键。

      可能更好的方法是将每个文件名/按钮分解为自己的迷你表单,在每个表单中创建一个隐藏字段,并将值设置为应转换的文件名。

      这样,当您发布时,您将拥有应该转换的文件的名称附加到您已经知道名称的密钥上

      【讨论】:

        【解决方案3】:

        使用 Ajax 请求执行此操作

        在您的 html 文件底部创建 javascript 函数 convert_video

        function convert_video(video_id){
        
            $.ajax({
                url: 'server.com/converttomp3.php',
                type: 'POST',
                data: {video_id:video_id},
                beforeSend: function(){
                    //
                },
                success: function(data)
                {
        
                    var crude = JSON.parse(data);
        
                    if(crude.status){
                        alert('Success message');
                        window.location.href = window.location.href;
                    } else {
        
                        alert(crude.message);
                    }
        
        
                },
                error: function (jqXHR, textStatus, errorThrown)
                {
                    //Error
        
                }
        

        然后从 HTML 作为您的循环视频

        <td><button type="submit" onclick="return convert_video('<?php echo $array['video_id'] ;')" name="go-button" value="Go">Go</button</td>
        

        终于在你的服务器端代码中

        if($_SERVER['REQUEST_METHOD'] == "POST")
        {    
          $video_id = $_POST['video'];
          // processs your video here .
         }
        

        【讨论】:

        • 不要忘记从
          标签中删除操作
        • 正在调查。会及时通知您。
        • 处理后,您还需要print json_encode($objectWithStatus&amp;Message)回复状态和消息,以通知用户是否成功
        • 你想让我在里面放什么? beforeSend: function(){ // },
        • 您可以开始制作 Go 按钮的动画以向用户显示处理已开始
        猜你喜欢
        • 2013-04-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-28
        • 2021-11-04
        相关资源
        最近更新 更多