jQuery:表单内的ajax POST-防止在ajax调用中提交表单 [英] jquery: ajax POST inside a form - prevent form submission on ajax call

查看:97
本文介绍了jQuery:表单内的ajax POST-防止在ajax调用中提交表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表单(Drupal节点编辑表单)内执行ajax调用,但似乎在执行调用时出于某种原因提交了表单。以下是示例代码:

I am trying to perform an ajax call inside a form (a Drupal node edit form) , but it seems when performing the call, it submits the form for some reason. Here is a sample code:

jQuery.ajax({
     type: "POST",
     url: "my_custom/url",
     dataType: "html",
     data: {"text": jQuery("#edit-body").html()
      },
     success: function(result){
        console.log(result);
     }
    });  

我可以通过在控制台中执行它来复制它,但是我将其附加到按钮单击功能上在表格内。关于阻止表单在POST ajax调用中提交的任何提示?

I can replicate this just by executing it in the console, but I attach this to a button click function inside the form. Any tips on preventing the form from submitting, on a POST ajax call?

此处是要求的完整代码

        jQuery("#edit-body").before('<div id="proofread_bot-button-holder"><button type="button"  id="proofread_bot-submit" onclick="return false;">Check with Proofread Bot</button></div>'); 
    jQuery("#proofread_bot-submit").click(function(event){
      event.preventDefault();
      jQuery("#proofread_bot-button-holder").append("<img id=\"proofread_bot_throbber\" src=\"sites/all/modules/proofread_bot/images/throbber.gif\" />");

      jQuery.ajax({
         type: "POST",
         url: "proofread_bot/check",
         dataType: "html",
         data: {"text": jQuery("#edit-' . variable_get('proofread_bot_field') . '").html()
          },
         success: function(proofread_result){
            jQuery("#proofread_bot-submit").after(proofread_result);
            jQuery("#proofread_bot_throbber").remove(); 
         }
        });    
      });


推荐答案

您需要覆盖表单的onsubmit事件以防止提交:

You need to override form's onsubmit event to prevent submitting:

$("formSelector").bind('submit', function (e) {
    var isValid = someYourFunctionToCheckIfFormIsValid();
    if (!isValid) {
        e.preventDefault();
        return false;
    }
    else {
        jQuery.ajax({
            type: "POST",
            url: "my_custom/url",
            dataType: "html",
            data: { "text": jQuery("#edit-body").html()
            },
            success: function (result) {
                console.log(result);
            }
        });
        e.preventDefault();
        return false;
    }
});

通过致电

e.preventDefault();
return false;

您可以防止同步回发的发生。

You prevent synchronous postback from occurring.

更新:
如果不想覆盖表单提交,也许可以将按钮放在表单标签之外(如果需要,可以使用CSS调整位置)?

UPDATE: If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?

这篇关于jQuery:表单内的ajax POST-防止在ajax调用中提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆