我正在尝试将一些值从前端发送到Django应用程序。我想操纵这些值然后重定向到另一个视图,但似乎Django没有重定向也没有渲染任何东西。
这是我的urls.py
from django.conf.urls import url
from . import settings
from personality_form import views
urlpatterns = [
url(r'^$', views.home, name="home"),
url(r'^apiLogin/(?P<_id>\d+)$', views.apiLogin,name="apiLogin"),
url(r'^formulario/(?P<_id>\d+)$', views.formulario, name="formulario"),
]
这是我的views.py
from django.shortcuts import render, redirect
from personality_form.models import *
from personality_form.forms import *
from django.views.decorators.csrf import csrf_exempt
def home(request):
return render(request, 'index.html')
def formulario(request, _id):
if (request.method == 'POST'):
form = personalityForm(request.POST)
else:
form = personalityForm()
return render(request, 'formulario.html', {'form': form})
@csrf_exempt
def apiLogin(request, _id):
if (request.method == 'POST'):
return redirect('/formulario/'+_id)
这是我用来从前面发送POST请求的javascript函数。
function test() {
var http = new XMLHttpRequest();
http.open('POST', '/apiLogin/1234', true);
http.setRequestHeader('Content-type', 'application/json');
var payload = {userID: "1234", access: "4567"};
var params = JSON.stringify(payload);
// Send request
http.send(params);
}
我尝试将POST发送到apiLogin视图。我检查它是否正在进入该视图但是当我尝试重定向到公式视图时,它输入公式代码但似乎不执行渲染指令。我试图更改渲染的重定向功能,但不显示新的html。
有没有理由不重定向网址并改变前端?
我正在使用Django 1.11和Python 3.6。
答案 0 :(得分:0)
您必须稍微更改代码。
在api_login()
中,使用参数创建反向网址。然后在JavaScript中更改窗口URL本身以重定向。
首先,在def apiLogin(request, _id)
:
from django.core.urlresolvers import reverse
from django.http import JsonResponse
@csrf_exempt
def apiLogin(request, _id):
if (request.method == 'POST'):
#create a url string using reverse.
url = reverse('formulario' , kwargs = {'_id' : _id})
#if the above way doesn't work then try: url = request.build_absolute_uri(reverse('formulario' , kwargs = {'_id' : _id}))
#Now simply return a JsonResponse. Ideally while dealing with ajax, Json is preferred.
return JsonResponse(status = 302 , data = {'success' : url })
然后在你的JavaScript中:
function test() {
var http = new XMLHttpRequest();
//The onreadystatechange function is called every time the readyState changes.
//4: request finished and response is ready
//basically the below function gets called every time your the response of you request request is returned from the server.
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 302) {
var json = JSON.parse(this.responseText);
console.log(json.success);
//following line would actually change the url of your window.
window.location.href = json.success;
}
};
http.open('POST', '/apiLogin/1234', true);
http.setRequestHeader('Content-type', 'application/json');
var payload = {userID: "1234", access: "4567"};
var params = JSON.stringify(payload);
// Send request
http.send(params);
}
我希望这有效。如果没有,请检查控制台内打印的内容。如果它工作,那么只需删除控制台语句。
希望这会有所帮助。感谢。