簡體   English   中英

Fetch API 請求的服務器端未收到數據

[英]server side of Fetch API request doesn't receive data

我正在通過 Fetch 發送帶有POST請求的數據,但看起來好像服務器端沒有收到數據。 你會發現代碼之后會發生什么。

客戶發布請求

const formMobile = document.getElementById('quoteMobile');
if (formMobile) {
    formMobile.addEventListener('submit', function(e){  
      e.preventDefault()

console.log("submit fired");
console.log(            
                document.getElementById('fromDate').value +
                document.getElementById('toDate').value +
                 document.querySelector('input[name="unit"]:checked').value + 
                 document.getElementById("total").value +
                document.getElementById("lan").value
);
    
     fetch('/api/apicreatebooking.php', {
          method: 'POST',
          body: JSON.stringify({        
                fromDate: document.getElementById('fromDate').value,
                toDate: document.getElementById('toDate').value,
                apptmnt: document.querySelector('input[name="unit"]:checked').value,
                total: document.getElementById("total").value,
                lan: document.getElementById("lan").value
          }),
          headers: {
            'Content-type': 'application/json; charset=UTF-8',
          }
      })
    .then(function(response){ 
        return response.json()})
    .then(function(data){
console.log(data)
        body=document.getElementById("bodyDiv")
        messages=document.getElementById("messagesDiv");
        if (data.success) {
            bookingCode = data.bookingCode;
            phpFile = 'mbooking_form_content2.php'
            $('#bodyDiv').load('/presentation/' + phpFile + '?bookingCode=' + bookingCode);
        } else {
            messages.innerHTML = data.message;
        } 
    }).catch(error => console.error('Error:', error)); 
    });
    
}   

服務器端

 <?php $a="a>"; if (isset($_POST['fromDate'])) {$a += $_POST['fromDate'];} if (isset($_POST['toDate'])) {$a += $_POST['toDate'];} if (isset($_POST['apptmnt'])) {$a += $_POST['apptmnt'];} if (isset($_POST['total'])) {$a += $_POST['total'];} if (isset($_POST['lan'])) {$a += $_POST['lan'];} $result = array( "success" => true, "message" => $a, "bookingCode" => '1234567' ); $output = json_encode($result); echo $output;

從第二個客戶端console.log ,我看到所有數據都存在。 服務器端也返回$result數組,但是,它看起來像這樣(客戶端console.log : {success: true, message: "a>", bookingCode: "1234567"} 。所以傳輸的數據都沒有收到 - 或者至少我不能用$_POST收到它。

由於某些奇怪的原因,我發現 Fetch API 的服務器端文檔很少,但我的理解是它像任何 POST 請求一樣工作(如果使用 POST 請求)。 我還找到了一個答案,其中有人從成功中刪除了內容類型並變得幸運,在這里不起作用。

您的 fetch 請求正在將 json 發送到服務器,服務器不期望 json,它期望表單數據。
您可以使用 URLSearchParams 對象將該類型的數據發送到您的服務器。

 fetch('/api/apicreatebooking.php', {
      method: 'POST',
      body: new URLSearchParams ({        
            fromDate: document.getElementById('fromDate').value,
            toDate: document.getElementById('toDate').value,
            apptmnt: document.querySelector('input[name="unit"]:checked').value,
            total: document.getElementById("total").value,
            lan: document.getElementById("lan").value
      })
  })

如果你真的想從客戶端發送 JSON,你必須改變你在服務器上讀取它的方式。 數據不存儲在 $_POST 中,您必須從標准輸入讀取它。

<?php
$a="a>";
$json = file_get_contents("php://input");
$data = json_decode($json);
if (isset($data['fromDate'])) {$a += $data['fromDate'];}
if (isset($data['toDate'])) {$a += $data['toDate'];}
if (isset($data['apptmnt'])) {$a += $data['apptmnt'];}
if (isset($data['total'])) {$a += $data['total'];}
if (isset($data['lan'])) {$a += $data['lan'];}
$result = array(
    "success" => true,
    "message" => $a,
    "bookingCode" => '1234567'
);

$output = json_encode($result);
echo $output;

上面來自 Musa 的第二個代碼片段有一個小問題。

它必須是$data = json_decode($json, true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM