Tej*_*wee 2 html javascript php fetch-api
我正在尝试使用 JS fetch API 发布表单数据,我也成功发送数据并获取响应,但在文件上传中出现错误,我的文件未上传,并且也没有将存储的文件名存储到数据库中。
<form id="signup">
<label for="myName">Send me your name:</label>
<input type="text" id="myName" name="name" value="abc">
<br>
<label for="userId">your id:</label>
<input type="text" id="userId" name="id" value="123">
<br>
<label for="pic">your photo:</label>
<input id="profile" name="profile" id="profile" type="file">
<br>
<input id="postSubmit" type="submit" value="Send Me!">
</form>
Run Code Online (Sandbox Code Playgroud)
和 JavaScript 代码
const thisForm = document.getElementById('signup');
const profile = document.getElementById('profile');
thisForm.addEventListener('submit', async function (e) {
e.preventDefault();
const formData = new FormData(thisForm).entries()
formdata.append("profile",profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: JSON.stringify(Object.fromEntries(formData))
});
const result = await response.json();
console.log(result);
Run Code Online (Sandbox Code Playgroud)
无需转换为JSON,也无需entries()在FormData上使用。还要检查拼写,您写的formdata与 不同formData。
const thisForm = document.getElementById('signup');
var formData = new FormData(thisForm);
const profile = document.getElementById('profile');
formData.append("profile", profile.files[0]);
const response = await fetch('<?php echo base_url() . 'api/get_subscription' ?>', {
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
body: formData
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20229 次 |
| 最近记录: |