簡體   English   中英

如何使用 fetch 將數據發布到 php

[英]how to use fetch to post data to php

我正在嘗試使用我的瀏覽器上的鏈接為我的 nativescript 應用程序創建評論 function,此功能工作正常。 but using the fetch API in my app, it returns the error function (error message is unexpected token < in JSON at position 0)

function AddCommentViewModel() {
      const viewModel = observableModule.fromObject({});
      var comm = "nice guy";
      var email = appSettings.getString("email");
      var phone = appSettings.getString("number");
        alert(comm);
        alert(email);
        alert(phone);
        var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email" + email + "&number=" + phone + "&comment=" + comm;
        fetch(url).then((response) => response.json()).then((res) => {
    viewModel.set("itemsd", res.itemss);
            alert("successful");
     }).catch((err) => {
            alert("failed");
    });
      return viewModel;
    }

我的 php 是

<?php 

include 'config.php';
$number = $_GET['number'];
$comment = $_GET['comment'];
$email = $_GET['email'];
try {
    $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
    $sql = "SELECT name FROM searchResults WHERE email='$email'";
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->prepare($sql);  
    //$stmt->bindParam(":email", $_GET['email']);
    $stmt->execute();
    $employees = $stmt->fetch(PDO::FETCH_ASSOC);
    $employees1 = $stmt->fetchAll(PDO::FETCH_OBJ);
    $name = $employees['name'];
    $sql1 = "INSERT INTO comments (number, comment, user, date) VALUES ('$number', '$comment', '$name', '02/04/2020')";
    $sth = $dbh->query($sql1);
    $sth->execute();
    $dbh = null; 
    echo '{"itemss":'. json_encode($employees1) .'}';
    //$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
} catch(PDOException $e) {
    echo '{"error":{"text":'. $e->getMessage() .'}}'; 
}

?>

錯誤Unexpected token < in JSON at position 0很可能意味着你得到了 HTML 而不是 Z0ECD1F8D148。 (想象一下將<html>.....解析為 JSON - 那么第一個字符是<這不是有效的 JSON。)

您可以暫時使用response.text()而不是response.json() ,然后打印您得到的res ,這樣您就可以在將其解析為 JSON 失敗之前查看實際內容。 (理想情況下,您會使用調試代理來查看實際發生的情況,或者只使用DevTools並查看網絡選項卡!)

我假設您的服務器顯示錯誤,並將其顯示為 HTML。

實際上,我在您的代碼中發現了另一個問題,這可能是您的請求無效的原因:

var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email" + email + "&number=" + phone + "&comment=" + comm;

這里的代碼有"?email" + email會生成類似?emailjohn@doe.com的東西,這可能不是你想要的。 您在此處缺少等號: "?email=" + email

但這還有另一個問題,您沒有對值進行編碼。 如果 email 設置為john&alice=bob@doe.com怎么辦? 然后你會有?email=john&alice=bob@doe.com你也不想要。 (或者想象一個包含&評論文本,這更有可能。)

如果這是在瀏覽器或 node.js 中,您最好使用URL object,但在 ZC86D2DA2845FFBD0C487 因此,您只需使用encodeURIComponent對每個單獨的值進行編碼:

var url = "https://adekunletestprojects.000webhostapp.com/skog/addComment.php?email=" +
  encodeURIComponent(email) + "&number=" + encodeURIComponent(phone) + "&comment=" +
  encodeURIComponent(comm);

或者,您可以編寫一個幫助程序 function 為您完成此操作,並獲得更簡潔的代碼:

const buildQuery = params => Object.entries(params)
  .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
  .join('&')

// Later on:
const query = buildQuery({ email: email, number: phone, comment: comm })
const url = `https://adekunletestprojects.000webhostapp.com/skog/addComment.php?${query}`

暫無
暫無

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

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