【问题标题】:AJAX and JQuery form Subscription problems with codeAJAX 和 JQuery 表单订阅问题的代码
【发布时间】:2019-11-10 10:36:06
【问题描述】:

我正在自己学习 jQuery,并且仍在编写自己的 Mailchimp Opt-In 表单代码。我知道已经问过关于这个问题的其他问题,但我想了解为什么我自己的代码不能作为一个 nooby jQuery 学生。我不想复制别人的代码,我只想让我的代码工作。

我已经将 post-json?u=&c=? 放在了动作中。 所以,这是我的 html 代码:(只需用 cmets 看 div)

<div id="mc_embed_signup">
            <form action="https://xxxxxxxxxx.com/subscribe/post-json?u=xxxxxx;id=xxxxx&c=?" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>


                <div id="mc_embed_signup_scroll">

                    <div id="colonna-sx">

                        <div class="mc-field-group gruppo-email">                       
                            <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">

<!-- THIS ONE -->
                            <div id="obbligo-email" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                        </div>


                        <div class="mc-field-group gruppo-nome">                        
                            <input type="text" value="" name="FNAME" class="required" id="mce-FNAME">

<!-- THIS ONE -->
                            <div id="obbligo-nome" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                        </div>

                        <div class="clear"></div>

                        <div class="mc-field-group input-group gruppo-consenso">
                            <input type="radio" value="Acconsento al trattamento dei miei dati personali." name="CONSENSO" id="mce-CONSENSO-0"><label for="mce-CONSENSO-0">Acconsento al trattamento dei miei dati personali.</label>

<!-- THIS ONE -->
                            <div id="obbligo-consenso" class="obbligo-form" style="color:red">Campo obbligatorio</div>
                        </div>


                        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_6a6f3b7082472f64c07c2cad3_e065e0e3c4" tabindex="-1" value="">
                        </div>
                    </div>


                    <div id="colonna-dx">
                        <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="mc-button"></div>
                    </div>

                    <div class="clear"></div>
                </div>
            </form>
        </div>

如你所见,我有一些“div”,注释为“THIS ONE”,ID 为 #obbligo-email、#obbligo-nome 和 #obbligo-consenso,在我的 CSS 上带有“display: none”文件。因此,如果输入字段为空,我希望这 3 条错误消息出现或消失。

这是我的 jQuery 代码

(function($) {
       var $form = $("#mc-embedded-subscribe-form");
       var stato1;
       var stato2;
       var stato3;

       $("#mc-embedded-subscribe").bind("click", function(event){
              if (event) event.preventDefault();
              if ($("#mce-EMAIL").val()!=""){
                     $("#obbligo-email").css({"display":"none"});
                     stato1=true;
              } else {
                     $("#obbligo-email").css({"display":"block"});
                     stato1=false;
              },

              if ($("#mce-FNAME").val()!=""){
                     $("#obbligo-nome").css({"display":"none"});
                     stato2=true;
              } else {
                     $("#obbligo-nome").css({"display":"block"});
                     stato2=false;
              },

              if ($("#mce-CONSENSO-0").is("=checked")){
                     $("#obbligo-consenso").css({"display":"none"});
                     stato3=true;
              } else {
                     $("#obbligo-consenso").css({"display":"block"});
                     stato3=false;
              },

              if (stato1==true && stato2==true && stato3==true) {
                     register($form);
              }

       });

       function register($form) {
              $.ajax({
                     type: $form.attr('method'),
                     url: $form.attr('action'),
                     data: $form.serialize(),
                     cache: false,
                     dataType: 'json',
                     contentType: 'application/json; charset=utf-8',
              })
       };

}(jQuery));

我试图理解在 StackOverFlow 上发送的其他答案但没有结果,所以我在这里看看是否有人可以帮助我理解我做错了什么。

在我看来,我希望在输入字段为空时显示 3 个错误消息,如果一切正常,则显示 3 个布尔变量。

如果 3 个布尔变量为真,那么使用 Ajax 发送表单,并且我不想重新加载页面,只需清除输入字段即可。

一些我不明白的信息:

PS:如果我将“方法”更改为“获取”,则会出现 404 错误页面。

PSS:如果我使用“$(document).ready(funtion(){”,则 javascript 文件不起作用(我尝试通过警报知道它,但我不知道为什么)。

【问题讨论】:

  • 检查浏览器开发工具 (f12) 的 javascript 控制台,您应该会看到语法错误消息,因为在您不应该使用逗号 (,) 的地方
  • 另外,serialize() 会生成名称值对查询字符串(例如 k=v&amp;v=k),而不是您将传出内容类型设置为 contentType: 'application/json; charset=utf-8' 的 json
  • 嗨,我改了逗号还是不行
  • 嗨@PatrickEvans,那我有什么用呢?我看到其他代码使用它(并且表单工作正常),所以这就是我写的原因:(
  • 如果控制台中没有任何内容,那么您的代码根本没有运行。您是否正确地将脚本包含在页面中。

标签: javascript jquery ajax forms


【解决方案1】:

在您的 jQuery 代码中,您有一些语义语法错误。你用逗号结束你的 if/else ......这是错误的。当你结束你的 if/else 时,你应该只使用花括号 {},大括号后面没有任何逗号。

另外你在 jQuery 中的检查有误:

if ($("#mce-CONSENSO-0").is("=checked"))

你应该使用:checked。不是=checked。所以你应该这样写:

if ($("#mce-CONSENSO-0").is(":checked"))

我可以试着回答你的 PS 问题:

PS: 正如我所见,您向某个外部 API 端点 https://xxxxxxxxxx.com/subscribe/post-json[...] 发出 POST 请求。正如我们在这里看到的,这个端点可能只处理 POST 请求,没有 GET 请求,所以你得到 404 错误(服务器找不到请求的资源。)。更多关于状态码:https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404

【讨论】:

  • 您好,感谢您的回答!顺便说一句,我看到其他带有 get 请求的代码,所以这就是我不明白的原因
【解决方案2】:

同时删除 Json 对象的最后一个键/值上的逗号

              $.ajax({
                 type: $form.attr('method'),
                 url: $form.attr('action'),
                 data: $form.serialize(),
                 cache: false,
                 dataType: 'json',
                 contentType: 'application/json; charset=utf-8',
          })

去掉这一行的逗号

contentType: 'application/json; charset=utf-8',

以下是代码示例:

            $(function(){

                $("[type=submit]").on("click", function(e){

                    // ---Prevent the form from submiting

                    e.preventDefault();

                    let errorFound = false;


                    // --- Check if fields are empty, if so show an exclamation mark icon

                    if($("[type=text]").val() == ""){
                        $("[type=text]").css("background", "url('exclamation-outline.svg') no-repeat right");
                        errorFound = true;
                    }
                    
                    if($("[type=text]").val() == ""){
                        $("[type=text]").css("background", "url('exclamation-outline.svg') no-repeat right");
                        errorFound = true;
                    }
                    

                    // --- Process form
                    if(errorFound == false)
                    register($("form"));

                });




                function register($form) {

                    

                    $.ajax({
                        
                            type: $form.attr('method'),
                            url: $form.attr('action'),
                            data: $form.serialize(),
                            cache: false,
                            dataType: 'json',
                            contentType: 'application/json; charset=utf-8'

                    });

                };



            });
            * { margin: 0px; padding: 0px; box-sizing: border-box; }
            ul{ list-style: none; }
            body, html { height: 100vh;  }
            input{ outline: none; border: none; background: none;  }
            h1, h2, h3, h4, h5, h6{ font-weight: normal; }
            p, li, a, h1, h2, h3, h4, h5, h6{ user-select: none; } 
            body{ display: flex; justify-content: center; align-items: center; }
            input{ height: 48px; display: block; width: 320px; margin-bottom: 24px; }
            input:not([type=submit]){ border-bottom: 1px dashed grey;  }
            input[type=submit]{ background: grey; border-radius: 4px; cursor: pointer; color: white; }
        <form action="?user=login" method="POST" >
            <input type="text" placeholder="Username" />
            <input type="password" placeholder="password" />
            <input type="submit" />
        </form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2013-09-25
    • 2023-03-04
    相关资源
    最近更新 更多