我正在使用 fetch API 提交表單資料,然后我想在 HTML 表中顯示一些變數值。但它并沒有像它應該的那樣作業。我能夠在views.py 中獲取表單資料,但我無法將其發送回HTML 檔案以在表格上顯示相同的資料。如果沒有 fetch API 提交,一切都按照我的需要正常作業。我不明白我的錯誤是什么。我試圖洗掉所有不必要的部分進行除錯。請讓我知道我哪里出錯了。
視圖.py
from json import dumps
def home(request):
context={}
if request.method=="POST":
options_value=request.POST.get('options_value')
value=request.POST.get('value')
print(type(options_value),value)
context={
'options_value':options_value,
'value':value,
}
print(context)
dataJSON = dumps(context)
return render(request, 'index.html', {'data':dataJSON})
return render(request, 'index.html')
索引.html
<form method="POST" action="" id="form">
{% csrf_token %}
<select
class="form-select"
aria-label="Default select example"
name="options_value"
id="options_value"
>
<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>
<input
type="text"
class="form-control"
type="text"
placeholder="Enter Value"
name="value"
id="value"
/>
<input
class="btn btn-primary"
type="submit"
value="Submit"
style="background-color: #3a0ca3"
/>
</form>
<table style="display: table" id="table">
<tbody>
<tr>
<th scope="row">ProfileUID :</th>
<td>{{data.options_value}}</td>
</tr>
<tr>
<th scope="row">First Nane :</th>
<td>{{data.value}}</td>
</tr>
</tbody>
</table>
<script>
let form = document.getElementById("form");
let options_value = document.getElementById("options_value");
let val = document.getElementById("value");
const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value;
form.addEventListener("submit", (e) => {
e.preventDefault();
const newform = new FormData();
newform.append("options_value", options_value.value);
newform.append("value", value.value);
newform.append("csrfmiddlewaretoken", csrf);
fetch("", {
method: "POST",
body: newform,
})
.then(response => response.text())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
});
</script>
uj5u.com熱心網友回復:
您可以使用document.write()從獲取請求中收到的資料重寫頁面的 html。
fetch(url,option) // Abstracted for brevity
.then(response => response.text())
.then(data => {document.write(data);})
雖然這可以滿足您的需求,但是,它并不是更新檔案中值的最佳方式。通過重寫檔案的整個 HTML,所有樣式表、影像和腳本都必須重新加載和執行,這是不必要的。此外,注入這樣的腳本是危險的。
如果您正在執行諸如將表單結果保存到資料庫等操作,最好將JSONResponse指示操作結果的 a 回傳到fetch請求中,然后使用 JavaScript 更新 HTML。
前任。
視圖.py
from django.http import JSONResponse
def home(request):
if request.method == "POST":
# Operations
if success:
return JSONResponse(
{
"successful": True,
"message": success_message,
"data": {}, # Anything else you'd like to send, like Profile UID and Name
}
)
else:
return JSONResponse(
{
"successful": False,
"message": error_message,
"data": {}, # Anything else you'd like to send
}
)
# Handle other request methods
index.html的fetch請求
fetch(url, options)
.then(response => response.json()) // returns a promise that converts response to a JS Object
.then(data => { // data is a JS object, which is
// the same as the dictionary we had in views.py
if (data.successful === true) {
// You can set IDs for the `td` where you would like to update the values
// like "profile-uid" and "profile-name"
// data.data is the dictionary returned by the JSONResponse
// that has additional information, which is also converted to a JS Object
document.getElementById('profile-uid').textContent = data.data.puid;
document.getElementById('profile-name').textContent = data.data.pname;
}
else {
// Handle Errors
}
})
uj5u.com熱心網友回復:
只需使用JsonResponse
def home(request):
context={}
if request.method=="POST":
options_value=request.POST.get('options_value')
value=request.POST.get('value')
print(type(options_value),value)
context['options_value'] = options_value
context['value']= value
print(context)
return JsonResponse(context, safe=False)
return render(request, 'index.html')
并在你的JavaScript中這樣做
fetch("",
{
method: "POST",
body: newform,
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch(error => {
console.error('Error:', error);
});
uj5u.com熱心網友回復:
第一種選擇)如果您要發送獲取請求,我認為最好jsonify({'data':dataJSON})在同一網頁本身上使用和獲取資料。
第二個選擇)在您的前端 HTML 上,您可以通過像這樣存盤它來處理您的回應。JSON.parse('{{ context | tojson }}')在一個變數中。確保從您的views.py 中將背景關系作為JSON 物件傳遞
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/479981.html
標籤:javascript Python html django
