【发布时间】: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