简体   繁体   English

根据jQuery中的Ajax请求制作Ajax表单

[英]Making an Ajax form from an Ajax request in jQuery

The client is making a request to the server. 客户端正在向服务器发出请求。 I need to take part of that request, and make the form button work with Ajax. 我需要接受该请求的一部分,并使表单按钮与Ajax一起使用。

This piece of code works perfectly for links: 这段代码非常适合链接:

var pagination_render = function() {
    var pagination = $('.pagination a');
    pagination.each(function() {
        $(this).click(function(event) {
            load_server(this.href, '.houseindex');
            return false;
        });
    });
};
pagination_render();

I tried numerous things for making the Ajax button work, and this is one of the tries: 我尝试了许多使Ajax按钮起作用的方法,这是尝试之一:

var contact_user = function () {
    $('.expanded').find('#submit').each(function() {
        $(this).unbind('click');
    });

    $('.expanded').each(function() {
        $(this).find('#submit').click(function(event) {
            form_submit($(this).parent(), '.contactuser .msg');
            return false;
        });
    });
}

Whenever there is a successful Ajax call, it goes through all of the expanded items, and then binds a click event. 只要有一个成功的Ajax调用,它就会遍历所有展开的项目,然后绑定一个click事件。

Now, sometimes this code works, and sometimes it doesn't.. When it doesn't work, it disables other events (toggle links) I have set up. 现在,有时此代码有效,有时却无效。.当它无效时,它将禁用我设置的其他事件(切换链接)。 It seems as if I need to wait a few ms for it to load the component into the DOM.. Do I? 好像我需要等待几毫秒才能将组件加载到DOM中。

So I get that when you call contact_user you: 因此,当您致电contact_user时,您会得到:

  1. First unbind any previous binded click events from the submit button. 首先,从“提交”按钮取消绑定任何先前绑定的单击事件。 I see one possible problem there and is that you are looking for an id of #submit . 我在那里看到一个可能的问题,那就是您正在寻找ID为#submit的ID。 You should only have one id in a single page. 您在一个页面中只能有一个ID。 Therefore you only need to use $('#submit').each(...) or if you have several submit buttons in the page either use a class if there are several submit buttons inside an .expanded item or just use $('.expanded :submit') 因此,您只需要使用$('#submit').each(...)或者页面中有多个提交按钮,或者.expanded项中有多个提交按钮,请使用一个类,或者只使用$('.expanded :submit')
  2. Adding a custom event when clicking the submit button. 单击提交按钮时添加自定义事件。 Same thing, you can simplify this by $('.expanded :submit') or if you truly only have one button with an id of submit (quite confusing). 同样,您可以通过$('.expanded :submit')简化此操作,或者如果您确实只有一个ID为submit按钮(相当混乱),则可以简化此操作。 Go with $('#submit') . $('#submit')

In conclusion: 结论:

var contact_user = function(){
   $('.expanded :submit').unbind('click');
   $('.expanded :submit').click(function(){
      form_submit($(this).parent(), '.contactuser .msg');
      return false;
   });
};

the :submit selector will select all <input type="submit" /> . :submit选择器将选择所有<input type="submit" />

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

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