我有关于Django URL重定向的问题。代码的结构如下:
所有功能都被正确调用,GET请求已完成,但页面未在浏览器中重定向...
urls.py
urlpatterns = [
url(r'^reactors/$', views.reactors, name = 'reactors'),
url(r'^measurements/reactor/$', views.measurementReactor, name='measureReact'),
]
views.py
@login_required
def reactor(request):
if request.method == "POST" and request.is_ajax():
if request.POST.get('type') == "measurement" :
return redirect('/measurements/reactor/?ref='+request.POST.get('id'))
@login_required
def measurementReactor(request):
reactobj = reactor.objects.get(id=request.GET['ref'])
query = measurements.objects.filter(id_reactor=reactobj.id)
return render(request, "measureReact.html",{"query":query})
reactor.js
var table1 = $('#datatable').DataTable();
$('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () {
var data = $(this).parent().find("[name=pk]").text();
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
});
});
[编辑]感谢您的回答,我这样做了,它的确有效!
#views.py
import json
@login_required
def reactors(request):
if request.POST.get('type') == "measurement" :
data = json.dumps({'url':'/measurements/reactor/?ref='+request.POST.get('id')})
return HttpResponse(data)
#reactor.js
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
dataType: 'json',
success: function(data){
window.location.href = data["url"];
}
});
答案 0 :(得分:1)
在ajax调用中,你将获得json格式的数据,它不会更改url,最好使用HttpResponse从json返回url并从javascript代码重定向该url。
@login_required
def reactor(request):
if request.method == "POST" and request.is_ajax():
import josn
if request.POST.get('type') == "measurement" :
data = josn.dump({'url':/measurements/reactor/?ref='+request.POST.get('id')})
return HttpResponse(data)
在ajax调用成功方法中,使用$ window
捕获响应和重定向答案 1 :(得分:0)
正如 aman kumar 建议的那样,您的reactor视图应该将url
返回到reactor.js,然后使用它重定向到所需的页面:
var table1 = $('#datatable').DataTable();
$('#datatable tbody').on('click', 'tr>th:not(.controls.mdl-data-table__cell--non-numeric)', function () {
var data = $(this).parent().find("[name=pk]").text();
$.ajax({
type : "POST",
data : {'csrfmiddlewaretoken' : csrftoken, 'id':data, 'type':"measurement"},
success: function(data){
window.location.href = data.url;
}
});
});