如何使用提取 post 数据到 php

how to use fetch to post data to php

我正在尝试为我的 nativescript 应用程序创建一个评论功能,在我的浏览器上使用 link,这个功能工作正常。但是在我的应用程序中使用 fetch API,它 returns 错误函数(错误消息是意外标记 < 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 而不是 JSON。 (假设将 <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

但这还有另一个问题,您没有对这些值进行编码。如果电子邮件设置为 john&alice=bob@doe.com 怎么办?然后你会得到你也不想要的 ?email=john&alice=bob@doe.com 。 (或者想象一个 评论文本 包含 &,这是更有可能的。)

如果这是在浏览器或 node.js 中,您最好使用 URL 对象,但在 NativeScript 中您没有。因此,您只需使用 encodeURIComponent 对每个单独的值进行编码:

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

或者,您可以编写一个辅助函数来为您完成此操作,并获得更简洁的代码:

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}`