首先,让我们修复html。你并不需要
name或
id在您的按钮属性和因为你是在一个循环中写他们,他们不会是唯一的。只需将它们替换为。该
<input>标签不需要关闭
</input>。
一个
submit类型按钮有一个默认的行为(你不想与一个Ajax请求相结合)。您可以
e.preventDefault();像这样使用标签,也可以将标签更改为不会触发表单提交的标签。
未经测试的代码:
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_enpre(['message' => 'Failed']);} $f = $mp4_files[$_POST['id']];$parts = pathinfo($f); switch ($parts['extension']){ case 'mp4' : $filePath = $src_dir . DS . $f; system('C:ffmpegbinffmpeg.exe -i ' . $filePath . ' -map 0:2 -ac 1 ' . $destination_dir . DS . $parts['filename'] . '.mp3', $result); exit(json_enpre(['message' => 'Converted']);} exit(json_enpre(['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><?phpfor ($i = 0; $i < 3; ++$i) { echo "<div>{$i}: <button data-id="{$i}">Convert</button></div>";}?></body></html>convert.php
<?php$lookup = [ 'Good', 'Bad'];sleep(1);echo json_enpre(['message' => $lookup[$_POST['id']] ?? 'Error']);
效果如何:
-------------------------------------------启用->禁用… …->禁用
- 按钮#1文本进度:转换->正在转换…->良好
- 按钮#2文本进度:转换->正在转换…->错误(已启用)
- 按钮#3文本进度:转换->正在转换…->错误



