Fetch API post data不会将数据传输到Django的views.py中



我正在创建一个Django应用程序,为此我试图访问从POST请求收到的数据,使用JavaScript获取API,但它不工作。我可以看到,由于e.p preventdefault(),点击提交按钮后页面没有刷新;但是这些值根本没有被获取。我不知道我错在哪里。我已经尝试删除所有不必要的部分调试。请让我知道我哪里做错了。

views.py

def home(request):
if request.method=="POST":
options_value=request.POST['dropdown_val']
value=request.POST['val']
print(options_value,value)

index . html

<form method="POST" action="" id="form">
{% csrf_token %}

<div class="d-flex justify-content-center" style="margin-top: 6rem">
<div class="dropdown" style="display: flex" id="dropdown">
<select
class="form-select"
aria-label="Default select example"
name="options_value"
id="dropdown_val"
>
<option disabled hidden selected>---Select---</option>
<option value="1">Profile UID</option>
<option value="2">Employee ID</option>
<option value="3">Email ID</option>
<option value="4">LAN ID</option>
</select>
</div>
<div class="col-3 bg-light" style="margin-left: 2rem">
<input
type="text"
class="form-control"
id="in3"
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
</div>
<div style="margin-left: 2rem">
<input
class="btn btn-primary"
type="submit"
value="Submit"
style="background-color: #3a0ca3"
/>
</div>
</div>
</form>
<script>
let form = document.getElementById("form");
let dropdown_val = document.getElementById("dropdown_val");
let val = document.getElementById("value");
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;

form.addEventListener("submit", (e) => {
e.preventDefault();

const newform = new FormData();
newform.append("dropdown_val", dropdown_val.value);
newform.append("val", val.value);
newform.append("csrfmiddlewaretoken", csrf);
fetch("", {
method: "POST",
body: newform,
})

.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>

问题是您在输入字段中有2个id标记:

<input
type="text"
class="form-control"
id="in3"   <--- problem is here
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>

移除id='in3',它应该工作。您可以在提交表单时在浏览器的控制台中检查该错误。

最新更新