AJAX不支持jQuery加载表单

时间:2016-02-18 11:13:19

标签: php jquery ajax

我有一个用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;
});

1 个答案:

答案 0 :(得分:1)

我通常更喜欢坚持.on()功能,而不是速记等同。

阅读.on()手册页后,您会发现它需要selector参数:

  

选择

     

类型:字符串

     

用于过滤触发事件的所选元素的后代的选择器字符串。如果选择器为null或省略,则事件始终在到达所选元素时触发。

添加selector参数后,将委派事件而不是直接绑定(如.submit的情况)。直接绑定仅在元素已存在时才有效(因此它不适用于动态加载的内容)。

$(document).on('submit', '.chat_form', function() {
    // the rest of the code
});