【问题标题】:preventDefault() cant work on('submit') functionpreventDefault() 不能在('submit') 函数上工作
【发布时间】:2018-11-15 15:24:31
【问题描述】:

我有这个代码:

<form action="/example/call/to/api" id="myId" enctype="multipart/form-data"  method="post">

在外部 .js 文件上我已经完成了这个功能:

$('#myId').on('submit',(function(e) {
  e.preventDefault();
    $.post("URL"+$(this).attr('action'), function(c) {
      var objJson = $.parseJSON(c);
      var url = objJson[0].url;
      $.ajax({
        ('#myId').on('submit',(function(e) {
           e.preventDefault();
           $.ajax({
             type:'POST',
             url: url,
             data:formData,
             cache:false,
             contentType: false,
             processData: false,
             xhr: function () {
             //some code here,      
             success:function(html){
             //some code here 

问题是我不需要重定向,但是现在提交表单时,我总是被重定向到 /example/call/to/api :/ 为什么在这种情况下 preventDefault 不能工作?

调用有效,问题是“preventDefault”不起作用!

已解决,我只是使用指向相同 ID 的相同函数来发出不同请求(通过每个表单内的操作)。 只是划分了每个动作的功能和所有的作品! 该函数只取代码中的第一个 ID 并忽略所有其他 ID。

【问题讨论】:

  • 你的提交处理程序被调用了吗?
  • 1.检查您的脚本是否确实添加到您的 html 中,2. 确保它包含在 document.ready 函数中,3. 检查您的控制台是否有错误
  • 抱歉,代码已更新!脚本在 html 中,文档准备好后开始,控制台没有错误。
  • 您的代码对我有用。问题必须在代码的其他地方。请提供一个可重现的例子。
  • ` $.ajax({ ('#myId').on('submit',(function(e) { `是错误的

标签: javascript ajax form-submit preventdefault


【解决方案1】:

您忘记了 ('#myId') 之前的 $ 或 jQuery,并且您在提交处理函数之前有一个额外的 (

$('#myId').on('submit', function(e) {
 e.preventDefault();
 $.ajax({
 type:'POST',
 url: url,
 data:formData,
 cache:false,
 contentType: false,
 processData: false,
 xhr: function () {
 //some code here
 },      
 success:function(html){
 //some code here 
 }
 });

您还需要确保在文档准备就绪时运行代码;否则,您的表单将不存在。

$(function(){
  $('#myId').on('submit', function(e) {
  e.preventDefault();
 $.ajax({
 type:'POST',
 url: url,
 data:formData,
 cache:false,
 contentType: false,
 processData: false,
 xhr: function () {
 //some code here
 },      
 success:function(html){
 //some code here 
 }
 });
});

【讨论】:

    【解决方案2】:

    你的点击事件必须看起来像这个

    ('#myId').on('submit', function() {...}
    

    不是('#myId').on('submit', (function() {...})

    只需删除函数开头和结尾处的(

    【讨论】:

    • 这是为什么呢?我不明白为什么这会阻止preventDefault() 被执行。不需要使用( ... ),我同意,但这不是错吧?
    猜你喜欢
    • 1970-01-01
    • 2012-05-20
    • 2021-10-02
    • 1970-01-01
    • 2017-10-29
    • 2017-07-15
    • 1970-01-01
    • 2022-06-27
    • 2023-03-12
    相关资源
    最近更新 更多