gpt4 book ai didi

javascript - 在同一个 View django中使用POST和GET

转载 作者:行者123 更新时间:2023-11-28 15:16:18 24 4
gpt4 key购买 nike

单击按钮(send_net)时,我想将存储在输入“文本”中的文本从 django 模板发送到 View 以及与该 View 关联的 url。

相关的html:

<div class="search_box">
<form id="target" action="." method="post">{% csrf_token %}
<input type="text" id = "sbox" placeholder="Search...">
<a href = "create_network" type="button" id="send_net"></a>
</form>
</div>

我使用 POST 请求将变量发送到 View :

$(document).ready(function(e){
$('#send_net').click(function(e){
var query = document.getElementById("sbox").value;
var d = {'query':query};
$.ajax( link, {
type: "POST",
data: d,
success: function(data) {
alert('call back');
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error, status = " + textStatus + ", " +
"error thrown: " + errorThrown
);
}
});
});

});

View .py

def create_network(request):
c={}
c.update(csrf(request))
r=[]
if request.method=='POST':
if 'query' in request.POST:
query = request.POST['query']
r.append({'id':1, 'label':query})
venues = Venue.objects.filter(title__contains="Life")
for venue in venues:
d={}
d['id'] = venue.id
d['label'] = venue.title
r.append(d)
data = json.dumps(r)
edges = [{'from':15505, 'to':19092}]
data_e = json.dumps(edges)
con = RequestContext(request, {"nodes":data, "edges":data_e})
return render_to_response('quir/network.html', c, con)

但是 r 永远不会有 '{'id':1, 'label':query}' 因为后续的 GET 请求会将其删除干净。如何将查询值保留在“r”中?我对 Django 和 javascript 比较陌生,如果这是初级的,我很抱歉。非常感谢。

最佳答案

您可以使用Class-based views并定义一种 GET 方法和另一种 POST 方法:

class CreateNetwork(View):  # Extend from the view you need

c = {}
r = []

def get(self, request, *args, **kwargs):

# This code will be executen in a GET request

# here you can access c or r with self
self.c.update(csrf(request)) # this is just an example
...

def post(self, request, *args, **kwargs):

# This code will be executed in a POST request

self.r.append(...)

关于javascript - 在同一个 View django中使用POST和GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33767248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com