简体   繁体   English

启用AJAX的表单仅使用AJAX提交一次,然后默认为HTTP请求

[英]AJAX-enabled form will only submit once using AJAX, then defaults to HTTP request

AJAX-enabled form will only submit once using AJAX, then defaults to using a standard HTTP request. 启用AJAX的表单仅使用AJAX提交一次,然后默认使用标准HTTP请求。 Code is below: 代码如下:

    $('#urlContainer form').submit(function(){

        var p = {};
        p['url'] = $('input#url').val();

        if($('#urlContainer #results').length != 0){
            $('#urlContainer #results').fadeOut(1000, function() {
                $('#urlContainer').load(location.href+' #urlContainer>*',p,function(){
                    $('#urlContainer #results').hide();
                    $('#urlContainer #results').fadeIn(1000);

                });
            });
        } else {
            $('#urlContainer').load(location.href+' #urlContainer>*',p,function(){
                $('#urlContainer #results').hide();
                $('#urlContainer #results').fadeIn(1000);

            });
    }
    return false;
});

Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

$('#urlContainer').load(...)

This code replaces all the content within #urlContainer . 此代码替换#urlContainer所有内容。 All the elements are replaced, which means that all event handlers bound to them will also be replaced. 所有元素都将被替换,这意味着绑定到它们的所有事件处理程序也将被替换。 You should use delegate() to run code for events on elements that may not exist yet: 您应该使用delegate()在尚不存在的元素上为事件运行代码:

$('#urlContainer').delegate('form', 'submit', function(){
    // the code from your submit handler
});

Alternatively, you could rewrite your code to avoid obliterating the form element, so the handler on it would persist. 另外,您可以重写代码以避免抹去form元素,因此该处理程序将继续存在。

The jQuery load function replaces the contents of the matched elements with the result of the AJAX call. jQuery load函数用AJAX调用的结果替换匹配元素的内容。 When that happens, the form that you are binding to is removed (or replaced), so the original event handler does not trigger. 发生这种情况时,将删除(或替换)您要绑定的表单,因此不会触发原始事件处理程序。

If you use .live('submit' ...) instead of .submit , it should resolve your issue: 如果使用.live('submit' ...)而不是.submit ,它将解决您的问题:

$('#urlContainer form').live('submit', function(){
    ...
});

The live method attaches to current and future elements that match the selector. live方法将附加到与选择器匹配的当前和将来元素。

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

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