我无法使用 AJAX 请求从站点发送表单。
单击提交按钮后,生成的请求出现在浏览器行中
h 5B%5D=
html
<form enctype="multipart/form-data" id="main-form">
<div class="form-em">
<div class="form-group">
<input type="text" name="name" class="fg-mr inpform-f" placeholder="Your name">
<input type="text" name="socialname" class="inpform-f" placeholder="Social @username">
</div>
<div class="form-group">
<div class="fg-mr fg-btn">
<input type="button" class="quantity-arrow-minus" value="-">
<input type="number" name="numberfo" class="quantity-num inpform-f" placeholder="No., of followers">
<input type="button" class="quantity-arrow-plus" value="+">
</div>
<div class="fg-btn">
<input type="email" name="email" class="inpform-f" placeholder="Your email">
</div>
</div>
<textarea name="text" rows="5" class="inpform-f" placeholder="Enter your message..."></textarea>
<div class="form-group">
</div>
<div class="form-group">
<input class="fg-mr fg-clear" id="clear-form" value="Clear form" type="reset">
<div class="fg-mr fg-wrap">
<input class="fg-mr fg-upload-none" type="file" name="myfile[]" multiple id="myfile" accept=".jpg" data-multiple-caption="{count} files selected" multiple>
<label id="upload-container" class="fg-upload" for="myfile"><strong>Load file</strong></label>
</div>
<button id="send-btn-form" class="fg-send button-f" type="submit" value="Send" onclick="submit()">Send message</button>
</div>
</div>
</form>
main.min.js
$(function() {
$("#main-form").on("submit", function(e) {
let doc = document,
formData = new FormData(),
formFile = doc.getElementById("myfile");
if (formFile.files && formFile.files.length == 1) {
file = formFile.files[0]
formData.set("myfile", file, file.name);
}
let nameForm = document.querySelector(".name");
formData.set("name", nameForm.value)
let socialnameForm = document.querySelector(".socialname");
formData.set("socialname", socialnameForm.value)
let numberfoForm = document.querySelector(".numberfo");
formData.set("numberfo", numberfoForm.value)
let emailForm = document.querySelector(".email");
formData.set("email", emailForm.value)
let textForm = document.querySelector(".text");
formData.set("text", textForm.value)
let request = new XMLHttpRequest();
request.open('POST', "php/send.php");
request.send(formData);
e.preventDefault();
});
});
php - 像这样接受
$name = $_POST['name'];
$socialname = $_POST['socialname'];
$numberfollow = $_POST['numberfo'];
$email = $_POST['email'];
$text = $_POST['text'];
$file = $_FILES['myfile'];
onclick="submit()"
并从中删除<button id="send-btn-form" class="fg-send button-f" type="submit" value="Send" onclick="submit()">Send message</button>
。为什么那里需要它?之后,在浏览器控制台中查找错误。 (稍后我会告诉你。)
以下是错误:
我在 MDN 上阅读了有关 FormData 的信息,并这样做了,它确实有效。
事实证明,不可能单独定义每个输入值。
FormData 将仅使用使用 name 属性的输入字段。