【问题标题】:Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise [duplicate]Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 Promise [重复]
【发布时间】:2020-03-26 12:13:47
【问题描述】:

我正在尝试将表单中的数据插入数据库。我尝试使用 Fetch 来做到这一点,所以一切都会更加动态。

这是我的 php 文件:

if (!empty($_POST['action'])) {
  if ($_POST['action'] == 'confirm') {
    $data =  array(
      'city_id' => $_GET['city_id'],
      'pub_id' => $_POST['pubs'],
      'beer_id' => $_POST['beers'],
      'snack_id' => $_POST['snacks'],
      'location_id' => $_POST['locations'],
      'daytime' => $_POST['daytime'],
      'participants' => $_POST['participants']
     );

  $insertedCrawl = $this->crawlsDAO->insertCrawl($data);
    if (!$insertedCrawl) {
      $errors = $this->crawlsDAO->validate($data);
      $this->set('errors', $errors);
    if (strtolower($_SERVER['HTTP_ACCEPT']) == 'application/json') {
      header('Content-Type: application/json');
        echo json_encode(array(
          'result' => 'error',
          'errors' => $errors
        ));
      exit();
    }

    $_SESSION['error'] = 'De crawl kon niet toegevoegd worden!';

    } else {
        if (strtolower($_SERVER['HTTP_ACCEPT']) == 'application/json') {
          header('Content-Type: application/json');
            echo json_encode(array(
              'result' => 'ok',
              'crawl' => $insertedCrawl
           ));
        exit();
      }

      $_SESSION['info'] = 'De crawl is toegevoegd!';
        header('Location: index.php');
        exit();
      }
    }
  }

在 Javascript 中,我尝试将此数据提取到 JSON。

这是我的 Javascript 代码:

const handleSubmitCrawlForm = e => {
  e.preventDefault();
  fetch($crawlForm.getAttribute("action"), {
    headers: new Headers({
    Accept: `application/json`
   }),
    method: "post",
    body: new FormData($crawlForm)
   })
      .then(r => r.json())
      .then(data => handleLoadSubmit(data));
      };

const handleLoadSubmit = data => {
  const $errorText = document.querySelector(`.error`);
  $errorText.textContent = "";
    if (data.result === "ok") {
      loadCrawls();
     } else {
       if (data.errors.text) {
         $errorText.textContent = data.errors.text;
       }
     }
   };

不知怎的,我最终得到了这个错误:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0

这是因为我向服务器发出请求并将响应解析为 JSON,但它不是 JSON。

【问题讨论】:

  • 您的 FormData 对象是否设置了 action$_POST['action']?如果没有设置操作值会怎样?

标签: javascript php promise fetch


【解决方案1】:

这看起来您的 PHP 文件返回的不是您期望它返回的 json 数组。

最常见的问题之一是 ?> 之后的尾随空格或换行符,如果您关闭了 php 标签,您可能需要检查这些标签。

您还可以使用 google chrome 控制台 -> 网络选项卡查看您的 PHP 提供的导致 JSOn 验证失败的确切响应。

【讨论】:

    猜你喜欢
    • 2017-12-15
    • 2021-03-02
    • 2019-08-14
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 2021-12-21
    相关资源
    最近更新 更多