未捕获(承诺)SyntaxError:JSON中的意外令牌<位于位置0承诺

时间:2019-12-01 20:06:39

标签: javascript php promise fetch

我正在尝试将表单中的数据插入数据库中。我尝试使用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。

1 个答案:

答案 0 :(得分:0)

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

最常见的邪教之一是在?>之后是否包含空格或换行符,如果您关闭了php标记,则可能需要检查这些标记。

您还可以使用google chrome控制台->“网络”标签来查看您的PHP提供的确切响应,该响应导致JSOn验证失败。