我有一个与jQuery一起运行的PHP脚本,用于打印一些Html,但是该表单无法工作,因为它是用AJAX加载的。当我手动放入HTML表单时,Ajax起作用了,所以即使在用AJAX加载表单时,我也如何使它工作。
下面是通过AJAX回传表单的PHP代码
echo "<form action='fetch_chat.php' method='post' class='chat_form' id='chatform_".$row['friends_user_id']."'>
<input type='hidden' name='friends_id' value='".$row['friends_user_id']."'/>
<input type='hidden' name='current_user' value='".$user_id."'/>
<input type='submit' class='chat_submit' name='submit' id='openchat_".$row['friends_user_id']."'/>
</form>";下面是表单的ajax代码,它不适用于ajax加载的表单。
$('.chat_form').submit(function() {
var data = $(this).serialize();
$.ajax({
url: "../fetch_chat.php",
type: "POST",
data: data,
success: function(data) {
$('*').html(data);
},
error: function() {
alert('ERROR');
}
});
return false;
});发布于 2016-02-18 11:20:05
我通常更喜欢使用.on()函数,而不是它们的速记函数。
一旦您阅读了.on()手册页面,您将注意到它接受了selector参数:
选择器 类型:字符串 一个选择器字符串,用于筛选触发事件的选定元素的后代。如果选择器为null或省略,则事件始终在到达选定元素时触发。
一旦添加了选择器参数,事件就会被委派,而不是直接绑定(如在.submit的情况下)。只有在元素已经存在的情况下,直接绑定才能工作(因此它不适用于动态加载的内容)。
$(document).on('submit', '.chat_form', function() {
// the rest of the code
});https://stackoverflow.com/questions/35479846
复制相似问题