将 JSON 数据从客户端发布到服务器端

时间:2021-02-10 02:29:08

标签: php json fetch

我正在尝试理解这个上传 JSON 数据的示例。

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_json_data

我不确定服务器文件 ( json-session.php ) 中的含义,所以我将其留空。我觉得一定有代码丢失,但我无法从 Mozilla 站点看到什么是为了让这个示例工作。我收到一个错误,提示 JSON 出现意外结束。

Ps,这个例子是我之前的问题的后续;虽然我已经切换到 PHP 版本 - 我正在尝试通过将数据从客户端发布到服务器来完成 floatlomas 回答的第一部分。

Using global variables properly in node.js or is there a better way of doing this?

这是我正在使用的代码

<!DOCTYPE html>
    <html>
      <head>
        <title>Buy cool new product</title>
        <link rel="stylesheet" href="style.css">
        <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
        <script src="https://js.stripe.com/v3/"></script>
      </head>
      <body>
    
      <form id="form1">
             <input onclick="clickFunction()" id="new-button" type="submit" value="click">
        </form>
    
      </body>
    
      <script type="text/javascript">
        function clickFunction() {
            const data = { username: 'example' };
    
            fetch('json-session.php', {
              method: 'POST', // or 'PUT'
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(data),
            })
            .then(response => response.json())
            .then(data => {
              console.log('Success:', data);
            })
            .catch((error) => {
              console.error('Error:', error);
            });
        }
    
    
      </script>
    </html>

0 个答案:

没有答案