简体   繁体   English

AJAX不适用于jQuery加载的表单

[英]AJAX not working on jQuery loaded form

I have a PHP script which is run with jQuery to print out some Html forms however the form does not work because it is loaded with AJAX. 我有一个与jQuery一起运行的PHP脚本,用于打印出一些HTML表单,但是该表单无法正常工作,因为它已加载了AJAX。 When I manually put the HTML form in, the AJAX worked so how can I make it work even when the form is being loaded with Ajax. 当我手动放入HTML表单时,AJAX起作用了,所以即使使用Ajax加载了该表单,我也如何使它起作用。

Here is the PHP code that echos the form via 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>";

And here is the ajax code for the form which does not work with the ajax loaded 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;
});

I generally prefer to stick to .on() functions, rather than their shorthand equivalents. 我通常更喜欢使用.on()函数,而不是它们的简写形式。

Once you read the .on() manual page, you will notice that it takes the selector parameter: 阅读.on()手册页后,您会注意到它.on() selector参数:

selector 选择

Type: String 类型:字符串

A selector string to filter the descendants of the selected elements that trigger the event. 一个选择器字符串,用于过滤触发事件的所选元素的后代。 If the selector is null or omitted, the event is always triggered when it reaches the selected element. 如果选择器为null或省略,则事件在到达所选元素时始终被触发。

Once you add the selector parameter, the event is delegated instead of being directly bound (like in case of .submit ). 添加选择器参数后,将委派事件,而不是直接绑定事件(例如.submit )。 Direct bind only works if the element already exists (so it doesn't work for dynamically loaded content). 仅当元素已经存在时,直接绑定才有效(因此对于动态加载的内容无效)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM