簡體   English   中英

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

[英]How do I do this with javascript fetch

我正在檢查這個答案

它基本上是請求 Mailchimp 在用戶提交 email 時向用戶發送確認 email。

該代碼與 jquery 完美配合。但我不喜歡 jquery。而且只為這個小片段添加它有點煩人,因為我不會在我的項目的 rest 中使用它。 我已經嘗試使用 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...
            }
        }
    });
}

編輯有人建議我應該添加 HTML 表格:我這樣做是因為我想將用戶 email 發送到我的 MailChimp 訂閱列表。 但我希望它直接從我的網站執行此操作,而無需重定向到 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>

我還發現 jquery ajax 方法 get 接受數據參數,但它獲取數據內部的內容並將其添加到 URL。所以它仍然是一個沒有主體的 get 請求。 我正在嘗試找到一種方法來做到這一點,但使用 fetch 但不知何故 jquery URL 有一些我不知道它們來自哪里的東西。 我也嘗試使用 POST 方法執行此操作並獲取但顯然,服務器不允許這樣做。

值得一提的是 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

這就是我如何通過獲取來欺騙我的 URL 看起來像。 在這里我得到一個 CORS 錯誤

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

這就是我用 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)
        });
    } 



試試這個,這是您問題的確切解決方案(我希望)。 如果你仍然卡住,請評論下來,我會解釋。

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