【发布时间】:2026-02-21 14:15:02
【问题描述】:
我的 html 文件中有一个选择标记。我希望当用户更改他/她的选择时,我必须使用 ajax 的页面将用户选择的值发送到我的 views.py 函数,然后我用这个值重新创建页面。 我的html代码:
<div id="response>
<select name="page_length_name" id="page_length_id">
<option id="opt1">10</option>
<option id="opt2">20</option>
<option id="opt3">30</option>
<option id="opt4">40</option>
</select>
//here is a table
</div>
(此选择标签不在表单中)。我希望它被修复,直到用户更改数据。所以我想我必须使用cookie。我不知道我可以使用这样的功能,虽然选择不是形式?它应该是“POST”方法吗? post只能在表格中使用吗?如果是,那么我如何将数据(我的选择标签)发送到服务器?
$(function() {
$('#page_length_id').change(function() {
temp = ["page_length_id"].options[selectedIndex].value;
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
alert("success");
$("#response").html(data);
}
});
})
还有我怎样才能强制这个选择值在 cookie 中?只用views.py中的这行代码就够了吗?:
table_length = request.COOKIES.get('table_length')
这是我的 viwes.py:
def backup(request):
if request.is_ajax():
try:
table_length = request.COOKIES.get('table_length')
except Exception:
table_length = 10
if not page_length:
table_length = 10
//here i create the page with xsl and send it to a page to be shown
result = style.applyStylesheet(doc)
out = style.saveResultToString( result )
ok = mark_safe(out)
style.freeStylesheet()
doc.freeDoc()
result.freeDoc()
if request.method == 'POST':
return HttpResponse(ok)
else:
return render_to_response("show.html", {
'str': ok,
}, context_instance=RequestContext(request))
谢谢。
【问题讨论】:
-
问题太多。请说明您遇到的问题。你的方法会引发错误吗?另外,您是否使用 csrf 正确设置了 ajax 请求:docs
-
首先:我想知道如何将用户选择发送到服务器? (我没有表单,所以我想知道我可以使用 "$.ajax({type: "POST"..." 吗?我可以在没有任何表单的情况下使用 post 方法吗?)
-
当用户更改选择标签中的选项时没有任何反应。嗯...在我的另一个与 ajax 一起使用的视图函数中,我没有 csrf 并且它可以工作。