【问题标题】:Return submitted POST data with Alpine.js and new FormData()使用 Alpine.js 和 new FormData() 返回提交的 POST 数据
【发布时间】:2020-07-12 15:37:27
【问题描述】:

我正在尝试使用 Alpine.js 将一些表单数据发布到当前页面,然后 PHP $_GET 将使用这些数据来运行某些功能。

它似乎在响应中返回整个页面,而不是表单数据(然后由于它是无效的 JSON 而出错)。

如何在响应中只返回提交的表单数据?

<form
    method="post"
    action="./"
    class="form__press"
    x-on:submit.prevent="
        let formData = new FormData();
        formData.append('username', 'Chris');
        fetch('./', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
        .then((response) => response.json())
        .then((result) => {
          console.log('Success:', result);
        })
        .catch((error) => {
          console.error('Error:', error);
        });"
>
    <div class="field mb:15@xs">
        <label for="pressEmail">Email</label>
        <input type="email" name="pressEmail" autocomplete="off" required />
    </div>
    <div class="field mb:15@xs">
        <label for="pressPassword">Password</label>
        <input type="password" name="pressPassword" autocomplete="new-password" required />
    </div>
    <button type="submit" name="submit">Submit</button>
</form>

【问题讨论】:

    标签: alpine.js


    【解决方案1】:

    因此,正确的答案是您需要您的 PHP 后端函数以正确的内容类型(“application/json”)返回 JSON。

    但是你也可以实现这个客户端,因为你已经得到了你想要返回的所有数据。

    <form
        method="post"
        action="./"
        class="form__press"
        x-on:submit.prevent="
            let formData = new FormData();
            formData.append('username', 'Chris');
            fetch('./', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(() => JSON.parse(JSON.stringify(formData)))
            .then((result) => {
              console.log('Success:', result);
            })
            .catch((error) => {
              console.error('Error:', error);
            });"
    >
    

    【讨论】:

      猜你喜欢
      • 2019-10-06
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2017-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多