我有一个关于POST方法的问题。我正在尝试将表单中的数据记录到txt文件中。但是字符串是空的(在txt文件中我只有"请求:"(
HTML:
<form
action=""
method="POST"
id="form"
class="section-contact-me-form"
>
<fieldset>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="name">Name*</label>
<input
type="text"
name="name"
class="section-contact-me-input__input _req"
id="name"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="email">E-mail*</label>
<input
type="text"
name="email"
id="email"
class="section-contact-me-input__input _req _email"
>
</div>
<div class="section-contact-me-input">
<label class="section-contact-me-input__label" for="phone">Phone</label>
<input
type="text"
name="phone"
id="phone"
class="section-contact-me-input__input phone"
>
</div>
<div class="section-contact-me-textarea">
<label class="section-contact-me-textarea__label" for="message">Your message*</label>
<textarea
rows="10"
cols="45"
name="message"
id="message"
class="section-contact-me-textarea__textarea _req"
></textarea>
</div>
</fieldset>
<div id="submit" class="submit-button">
<button class="submit-button_active">Send data</button>
</div>
</form>
JS:
form.addEventListener("submit", formSend);
async function formSend() {
const formData = {
name: document.querySelector("#name").value,
email: document.querySelector("#email").value,
phone: document.querySelector("#phone").value,
message: document.querySelector("#message").value
};
const formDatatoSend = JSON.stringify(formData)
sendData("http://localhost:3000/101_susov_newDesign/contactme.php", formDatatoSend)
.then(() => {
form.reset();
})
.catch((err) => console.log(err))
};
const sendData = async (url, data) => {
const response = await fetch (url, {
method: "POST",
body: data
})
if (!response.ok) {
throw new Error (`URL with error ${url}, status ${response}`)
};
return await response;
};
PHP:
<?php
$value = $_POST['value'];
$f = fopen('file.txt', 'a+');
fwrite($f, "The request: ".$value."n");
fclose($f);
?>
因此,服务器工作正常:每次使用表单按钮时,都可以访问php代码并刷新txt文件,但从表单发送的内容是空的。正如我之前在txt文件中所说的;请求:";
我的代码中的eror在哪里?提前感谢,祝你今天愉快!
您没有名为value
的字段,因此$_POST['value']
不会返回任何内容。您可以通过添加每个字段的名称属性作为数组键来获得每个字段的值:
-
$value = $_POST['phone']
会在TXT文件中返回'The request: PHONE_NUMBER
'。 -
$value = json_encode($_POST)
会将整个帖子返回到您的TXT文件中
这应该有效:
$value = json_encode($_POST);