【发布时间】:2016-08-17 04:24:22
【问题描述】:
我正在尝试编译项目https://github.com/kannan4k/django-carpool 有关此问题,请参阅此项目 repo。
并在 ajax 调用期间出现以下错误。
加载资源失败:服务器响应状态为 400 (BAD REQUEST)。
我知道这是因为 ajax 发布请求和 CSRF 令牌。
以下是我的设置。
1.禁用"django.middleware.csrf.CsrfViewMiddleware"
2.在new_trip页面我有一个按钮(Postdata)所以这个按钮发送一个ajax请求。
我的看法:-
@login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax 调用 (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
此代码无法调用 /save_journey/ URL。 我从堆栈溢出中尝试了很多答案,但没有弄清楚问题出在哪里。
【问题讨论】:
-
很难找出问题所在,因为您正在捕获所有异常并在您的视图中简单地返回
403。打印所有例外情况并使用适当的详细信息更新问题。 -
您明确告诉您的代码在发生任何异常时返回错误请求。通过这样做,您已经小心地隐藏了任何可以让您或我们实际调试问题的信息。删除那个裸露的尝试/除外。
-
@v1k45 :- 感谢您的评论。我不能在这里发布整个代码,所以请查看 repo:-github.com/kannan4k/django-carpool 当我访问 /new_trip 页面时,有一个按钮调用 home.js 中的 PostData() 方法,它尝试调用 /save_journey/ 这导致问题。
-
我们不要求更多代码。只需删除 try/except 块并向我们展示您遇到的错误。
-
@v1k45:没有 Try/except 块,它给出了加载资源失败:服务器响应状态为 500(内部服务器错误)
标签: javascript jquery python ajax django