【问题标题】:Fetch SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON dataFetch SyntaxError:JSON.parse:JSON 数据第 1 行第 1 列的意外字符
【发布时间】:2020-01-24 11:42:53
【问题描述】:

我正在处理一个联系表单,这个错误正在阻止它工作......我可能正在监督一些事情。有趣的是,如果我使用 XMLHttpRequest 而不是 Fetch,我的代码就可以工作。

使用 Fetch 时,如果我不请求响应,它不会向我抛出任何错误,但也不起作用。如您所见,我正在调试正在传递的参数,它们没问题。

handleSubmit(e) 
    {

        /*var xhr = new XMLHttpRequest();

        xhr.addEventListener('load', () => {console.log(xhr.responseText)});

        xhr.open('POST', 'http://localhost:3002/index.php');

        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.send(JSON.stringify(this.state));*/


        fetch('http://localhost:3002/index.php',
        {
            method: "POST",
            body: JSON.stringify(this.state),
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
        }).then(
            console.log(JSON.stringify(this.state))
            ).then(
                (response) => (response.json())).then((response)=>
            {
                if (response.status === 'success')
                {
                    alert("Message Sent."); 
                    this.resetForm()
                }
                else if(response.status === 'fail')
                {
                    alert("Message failed to send.")
                }
            })

        e.preventDefault();

    }

以及来自 php 方面的响应:

...
                $sent = $mail->send();

                echo 'Message has been sent';

                if (isset($sent) && $sent === true) : ?> 
                {
                    "status": "success",
                    "message": "Your data was successfully submitted"
                }
                <?php endif;
            } 
            catch (Exception $e) 
            {
                echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
            }
        }
        else if (!empty($errors)) : ?> 
        {
            "status": "fail",
            "error":  <?php echo json_encode($errors) ?>
        }
        <?php endif;

【问题讨论】:

    标签: javascript reactjs fetch phpmailer


    【解决方案1】:
        async function handleSubmit(e) {
    
        const response = await fetch("http://localhost:3002/index.php", {
            method: 'POST', // *GET, POST, PUT, DELETE, etc.
            cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
            credentials: 'same-origin', // include, *same-origin, omit
            headers: {
                'Content-Type': 'application/json'
                // 'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: JSON.stringify(this.state) // body data type must match "Content-Type" header
        });
        if (response.status === 'success')
        {
            alert("Message Sent.");
            this.resetForm()
        }
        else if(response.status === 'fail')
        {
            alert("Message failed to send.")
        }
        e.preventDefault();
    }
    

    也可以看看using_fetch

    【讨论】:

      猜你喜欢
      • 2021-04-02
      • 2014-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多