简体   繁体   English

我如何使用 javascript fetch 执行此操作

[英]How do I do this with javascript fetch

I was checking out this answer .我正在检查这个答案

It's basically a request to Mailchimp to send a confirmation email to the user when they submit their email.它基本上是请求 Mailchimp 在用户提交 email 时向用户发送确认 email。

The code works perfectly with jquery. But I don't like jquery. And it's kind of annoying to have to add it just for this tiny snippet, since I won't be using it in the rest of my project.该代码与 jquery 完美配合。但我不喜欢 jquery。而且只为这个小片段添加它有点烦人,因为我不会在我的项目的 rest 中使用它。 I already tried "translating" this into vanilla javascript using fetch but it doesn't seem to work.我已经尝试使用 fetch 将其“翻译”为 vanilla javascript,但它似乎不起作用。

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",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}

EDIT Some suggested I should add the HTML form: I am doing all this because I want to send the user email to my MailChimp subscription list.编辑有人建议我应该添加 HTML 表格:我这样做是因为我想将用户 email 发送到我的 MailChimp 订阅列表。 But I want it to do it directly from my website without redirecting to the Mailchimp subscription page.但我希望它直接从我的网站执行此操作,而无需重定向到 Mailchimp 订阅页面。

<form action="https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&amp;id=0bf75ac6c4&c=?" method="get" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate newsletter__form" target="_blank">

      <label for="mce-EMAIL">Ingresa tu correo electrónico:</label>
      <input type="email" placeholder="ejemplo@gmail.com" value="" name="EMAIL" class="required textfield email__textfield" id="mce-EMAIL">
      <input type="submit" value="suscribirme" name="subscribe" id="mc-embedded-subscribe" class="button raise">

      <div id="mce-responses" class="clear">
        <div class="response" id="mce-error-response" style="display:none"></div>
        <div class="response" id="mce-success-response" style="display:none"></div>
      </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_070e69e5e3e6e664a8066e48f_0bf75ac6c4" tabindex="-1" value=""></div>
</form>

I also found out jquery ajax method get accepts the data argument but it takes what's inside of the data and adds it to the URL. So it's still a get request with no body.我还发现 jquery ajax 方法 get 接受数据参数,但它获取数据内部的内容并将其添加到 URL。所以它仍然是一个没有主体的 get 请求。 I am trying to find a way to do that but with fetch but somehow the jquery URL has things I don't know where they come from.我正在尝试找到一种方法来做到这一点,但使用 fetch 但不知何故 jquery URL 有一些我不知道它们来自哪里的东西。 I also tried doing this with POST method and fetch but apparently, the server doesn't allow that.我也尝试使用 POST 方法执行此操作并获取但显然,服务器不允许这样做。

For what is worth this is how the URL generated by jquery request looks like:值得一提的是 jquery 请求生成的 URL 看起来像这样:

 https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&id=0bf75ac6c4&c=jQuery35105022544193369527_1633147928440&EMAIL=email123456%40gmail.com&b_070e69e5e3e6e664a8066e48f_0bf75ac6c4=&_=1633147928441

And this is how I can trick my URL to look like with fetch.这就是我如何通过获取来欺骗我的 URL 看起来像。 Here I get a CORS error在这里我得到一个 CORS 错误

  https://herokuapp.us5.list-manage.com/subscribe/post-json?u=070e69e5e3e6e664a8066e48f&id=0bf75ac6c4&c=?&EMAIL=paula.uzcategui68%40gmail.com&b_070e69e5e3e6e664a8066e48f_0bf75ac6c4=

And this is what I'm doing with fetch这就是我用 fetch 做的

     function register(form) {
        data = new FormData(form);
        data = Object.fromEntries(data);
        data = Object.entries(data);
        let arroba = /@/gi;

        let action = form.getAttribute("action")+ "&"+ data[0][0] +"="+ data[0][1].replace(arroba, '%40') + "&" + data[1][0] + "=" + data[1][1]
       // console.log(action)
        fetch(action, {
            method: 'get',
            cache: 'no-cache',
            headers: {
                'content-type': 'application/json; charset=utf-8'
            },
        }) 
        .then(response => response.json())
        .catch(error => {
            alert("Could not connect to the registration server. Please try again later."+ error)
        });
    } 



Try this, it is the exact solution for your question (I hope).试试这个,这是您问题的确切解决方案(我希望)。 If you still get stuck please comment down, I will explain.如果你仍然卡住,请评论下来,我会解释。

async function register(form) {
    let data = new FormData(form);
    data = JSON.stringify(Object.fromEntries(data)); // convert formdata to json

    let response = await fetch(form.action, {
        method: form.method,
        body: data,
        cache: 'no-cache',
        headers: {
            'content-type': 'application/json; charset=utf-8'
        }
    })
    .then(response => response.json())
    .catch(error => {
        alert("Could not connect to the registration server. Please try again later.")
    });
}

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

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