【问题标题】:change button text in js/ajax after mp4 =>mp3 conversion in php在 php 中的 mp4 => mp3 转换后更改 js/ajax 中的按钮文本
【发布时间】:2019-10-25 06:23:40
【问题描述】:

我正在处理 html 表格行(目前是两个),如下所示,其中单击按钮:

=> JS/jQuery 代码被调用(其中 Go 文本更改为 Converting
=> 然后通过 AJAX 编写 convert.php 脚本,在该脚本中将 mp4 转换为 mp3

html/php代码:

  <?php  foreach ($programs as $key => $program) {  ?> 
       <tr data-index="<?php echo $key; ?>">
          <td><input type="submit"  id="go-btn" name="go-button" value="Go" data-id="<?php echo $key; ?>" ></input></td>
       </tr>
    <?php }?>

转换.php:

 $f = $mp4_files[$_POST['id']];
 $parts = pathinfo($f); 
 switch ($parts['extension'])
 {  
     case 'mp4' :
         $filePath = $src_dir . DS . $f;
         system('C:\ffmpeg\bin\ffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);    
         print_r("Hello World");
         break;                  
 } 

JS/jQuery 代码:

$("input[name='go-button']").click( function() {

  // Change the text of the button, and disable
  $(this).val("Converting").attr("disabled", "true");

});

只要单击上面 html/php 代码中的按钮,UI 中的文本就会从 Go 更改为 Converting因为我在我的代码库中添加了 JS/jQuery 代码,但是我添加的这个 JS/jQuery 代码只更改了文本。 它实际上并不知道转换是在后台发生的

问题陈述:

我想知道我需要在上面的 JS/jQuery 代码中做哪些修改,以便 UI 真正知道转换是在后台发生的。

可能,我们需要在 JS/jQuery 和上面的 php 代码之间添加 make 建立一些连接,但我不确定我们该怎么做。

【问题讨论】:

  • 您的问题并不完全清楚。如果“UI 确实知道正在发生转换”,您认为它应该是什么样子?你想看“Go”->“Converting”->“Converted”吗?

标签: javascript php ajax upload progress-bar


【解决方案1】:

首先,让我们修复 html。您的按钮不需要nameid 属性,它们不会是唯一的,因为您是在循环中编写它们。只需将它们替换为class="converter"&lt;input&gt; 标签不需要结束 &lt;/input&gt;

submit 类型的按钮具有默认行为(您不想与 ajax 请求结合使用)。您可以使用 e.preventDefault(); 之类的 this 或将标签更改为不会触发表单提交的内容。

未经测试的代码:

js

$(document).ready(function () {
    $("input.converter").click(function (e) {        
        e.preventDefault();
        let btn = $(this);
        btn.val("Converting").attr("disabled", "true");
        $.ajax({
            cache:    false,
            type:     "POST",
            dataType: "json",
            data:     {id: btn.data('id')},
            url:      "convert.php",
            success:  function(response) {
                btn.val(response.message).attr("disabled", response.message == "Converted" ? "false" : "true");
            },
            error: function (jqXHR, status, err) {
                console.log("Request failed: " + status);
            },
            complete: function (jqXHR, status) {
                console.log("Done. No matter the outcome");
            }
        });
        return false;
    });
});

php

if (empty($mp4_files[$_POST['id']])) {
    exit(json_encode(['message' => 'Failed']);
} 
$f = $mp4_files[$_POST['id']];
$parts = pathinfo($f); 
switch ($parts['extension'])
{  
    case 'mp4' :
        $filePath = $src_dir . DS . $f;
        system('C:\ffmpeg\bin\ffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result);    
        exit(json_encode(['message' => 'Converted']);
} 
exit(json_encode(['message' => 'Invalid File Type']);

这是一个快速演示(在本地测试可以工作):

main.php

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $("button").click(function (e) {        
        e.preventDefault();
        let btn = $(this);
        btn.html("Converting...").attr("disabled", "true");
        $.ajax({
            cache:    false,
            type:     "POST",
            dataType: "json",
            data:     {id: btn.data('id')},
            url:      "convert.php",
            success:  function(response) {
                btn.html(response.message)
                   .attr("disabled", response.message != "Bad"); // re-enables if Bad
            }
        });
    });
});
</script>
</head>
<body>
<?php
for ($i = 0; $i < 3; ++$i) {
    echo "<div>{$i}: <button data-id=\"{$i}\">Convert</button></div>";
}
?>
</body>
</html>

转换.php

<?php
$lookup = [
    'Good',
    'Bad'
];
sleep(1);
echo json_encode(['message' => $lookup[$_POST['id']] ?? 'Error']);

表现如何:

------------------------------------------- 启用 -> 禁用...... -> 禁用

  • 按钮 #1 文本进度:转换 -> 正在转换... -> 好
  • 按钮 #2 文本进度:转换 -> 正在转换... -> 错误(启用)
  • 按钮 #3 文本进度:转换 -> 正在转换... -> 错误

【讨论】:

  • 我在想的另一件事是当我在不同的机器上打开同一个网页时,它应该知道文件已经完成(意味着mp4的转换=>mp3已经完成)。在不同机器上打开页面时,Go button text 再次显示属于特定文件,这是不正确的,因为该文件已经完成。
  • 这是您发布的问题的新要求。您不应该在发布后更改您的要求。如果您愿意,可以发布一个新问题。如果我已经解决了最初的问题,让我们在继续之前把这个缝合起来。
  • 我添加了几个 php 脚本来快速演示我认为你想要什么。至于检查已经转换的内容,您需要将任何新转换的行保存到数据库表中,并检查它们是否在 main.php 和 convert.php 中进行了转换。这是一个太多的问题扩展,无法附加到此页面。 @flash
  • 我还有一个question。它不相似。我想知道你是否可以看看。
  • 谢谢。用户给出的答案很接近,但在某些情况下仍然失败。
【解决方案2】:

尝试改变这个:

$.ajax({
            url: 'convert.php',
            type: 'POST',
            data: {id: target}, //change to what you want
            success: function(res)
            {   
            },
            error: function(res)
            {
            }
        })

到这里:

$.ajax({
        url: 'convert.php',
        type: 'POST',
        data: {id: target}, //change to what you want
        success: function(res)
        {   
//You can add $(".go-btn").html('completed'); to here, but I prefer the other way.
        },
        error: function(res)
        {
// This is unnecessary if you are not gonna make it do anything if error occurs.
        }
    }) 
.done(function(data) {
$('.go-btn').html('Completed!');
//This fires when AJAX call suceeds the process. As a side note, "data" is what your .php code outputs, so you can do whatever you want to do with it.
});

还可以看看我的 cmets。 我希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-19
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    相关资源
    最近更新 更多