[英]How to update load context variable after change in django template via AJAX call?
[英]How to update Django variable passed through context using Ajax
我花了很多時間嘗試解決這個問題,我看到了很多解決方案,但我似乎無法將其解決。
因此,基本上,我在此視圖中傳遞了要在模板中顯示的數組和索引(視圖中的arr),該索引是我當前要顯示的數組的索引。 這意味着當我第一次加載頁面時,索引將為0,並且將顯示所述數組的第一個元素。 然后,我想更新此索引變量(通過單擊X按鈕),以便可以顯示數組的下一個元素(2、3和4)而無需重新加載頁面。 我以為可以使用Ajax查詢來執行此操作,但是我似乎無法獲取要在模板中更新的值。
先感謝您!
results.js
(function () { //automatically called as soon as the javascript is loaded window.addEventListener('load', main); }()); function update_display_counter(e, display_counter){ const $csrf_token = $('input[name="csrfmiddlewaretoken"]').attr('value'); display_counter++; $("#arr_counter").val(display_counter); $.ajax({ headers: { 'X-CSRFToken': $csrf_token }, url: "/establishments/results/", dataType: "json", type: "POST", data: { 'arr_counter': display_counter, }, success: function (json) { console.log(json) display_counter = json['sucess'] display_counter = parseInt(display_counter) $("#arr_counter").val(display_counter); }, }); return display_counter; } function main(){ const acceptBtn = document.getElementById('accept_btn'); const rejectBtn = document.getElementById('reject_btn'); let display_counter = 0; acceptBtn.addEventListener('click', (e) => { window.location.href = 'establishments/'; }); rejectBtn.addEventListener('click', (e) => { display_counter = update_display_counter(e, display_counter); }); }
view.py
def handle_results(request):
if request.method == "POST":
arr_counter = request.POST.get('arr_counter')
print("THIS IS: ", arr_counter)
return JsonResponse({"sucess": arr_counter})
else:
try:
coordinates = request.session['coordinates']
del request.session['coordinates']
display = handle_places_search(request, coordinates)
handle_transactions(request, display)
except request.ConnectionError as e:
print("Connection error: ", str(e))
except request.Timeout as e:
print("Timeout Error: ", str(e))
except request.RequestException as e:
print("RequestException Error: ", str(e))
except Exception as e:
print("Error: ", str(e))
return render(request, "results.html", context={"display": display, "arr": 0})
results.html
<!DOCTYPE html> <head> {% load staticfiles %} {% csrf_token %} {% block styles %} <link href="{% static 'main_tanto_faz/styles/index.css' %}" rel="stylesheet"> {% endblock %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="{% static 'results.js' %}"></script> <p hidden id="arr_counter">{{arr}}</p> </head> <body> <button type = "button" id="accept_btn">O</button> Testing: {{arr}} <button type = "button" id="reject_btn">X</button> </body>
您的代碼看起來不錯。 如果選中$("#arr_counter").val()
您將看到div的值很可能已正確設置。
請注意,瀏覽器開發人員工具並不總是直接在源代碼中反映value
變化,因此您不會在瀏覽器開發工具中看到<p hidden id="art_counter" value="3">0</p>
。
另外,將<p>
放在<head>
而不是在<body>
是一個奇怪的選擇。 它永遠不會顯示。 如果你只是想保持在JavaScript中變量的軌跡,只使用一個var
(的let
更多的現代的ECMAScript),並調整它的價值:
// In your template, initialise the var with a value from the context
var counter = {{ arr }};
// or if it's a string
var counter = "{{ arr }}";
// then when the you receive a new value through ajax:
counter = response.data.counter;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.