gpt4 book ai didi

javascript - 如何在jQuery和javascript上以ajax post方式播放声音效果?

转载 作者:行者123 更新时间:2023-12-03 11:59:10 25 4
gpt4 key购买 nike

我试图在将post方法的数据写入与php一起工作的mysql服务器并接收xml时播放声音效果。

所以我写了如下代码。当我写入数据时(点击#post_send按钮),声音效果很好,但接收数据时,声音不起作用。

我怀疑当播放声音片段在 ajax 或类似函数中时声音不起作用。

如何在ajax post方法中播放声音?

// Start Main code Area //
$(document).ready(function () {
// Global variable define area
curr_date = null;
last_date = "0000-00-00 00:00:00";
readAjax_timer = null;
audioElement = null;
// End of Global variable define area

audioElement = document.createElement('audio');
audioElement.setAttribute('src', './sound/bubble.mp3');

$("#post_send").click(function () {
audioElement.play();

curr_date = getTodayAndTime();
last_date = curr_date;

var str_postMsg = $("textarea").val();
if (str_postMsg == "") {
return;
}

appendShowBubble();
writeMsgToDB();
});

readAjax_timer = setInterval(function() {
readMsgByAjax();

}, 2000);

readMsgByAjax();

});
// End Main code Area //


这是接收数据的函数。

function readMsgByAjax() {
// receive a data from mysql by specified school name with ajax.
var sch_name = "wonderful_element_school";

var send_data = "sch_name=" + sch_name +
"&last_date=" + last_date;

// call ajax post method
$.post(
"PHP_readMsg_sql.php",
send_data,
function (data) {

$(data).find('tr').each(function () {

var db_record = $(this); //<= <tr>

// if "$(this)" is a table head, continue to next tr.
if (db_record.attr("id") == "head") {
return;
}

//////////////////////////////////////////////////
audioElement.play(); //<== This code doesn't work.
//////////////////////////////////////////////////

// process contents of tr.
var str_message;
var str_date;
var div_leftframe = $("#left_frame").clone();
div_leftframe.css("display", "block");

var p_message = div_leftframe.children('p');
str_message = db_record.find('td[id=post_message]').text();
str_message = str_message.replace(/\u000a/g, "</br>");

p_message.html(str_message);

var small_message = div_leftframe.children('small');
str_date = db_record.find('td[id=post_time]').text();
last_date = str_date;

str_date = str_date.replace(" ", " at ");

small_message.text(str_date);

$("#chat_list").append(div_leftframe);
});
}
);


$("#chat_list").append(div_leftframe);

var $target = $('html,body');
$target.animate({scrollTop: $target.height()}, 1000);
}

最佳答案

您必须在函数中传递 audioElement ,因为它超出了您的函数范围,正如 @scrowler 提到的那样。因此,您可以在 document.ready() 范围中添加该函数,也可以将函数更改为:

function readMsgByAjax(audioElement){}

当您在 document.ready() 代码中调用它时,只需执行以下操作:

readMsgByAjax(audioElement);

关于javascript - 如何在jQuery和javascript上以ajax post方式播放声音效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25478347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com